Ejemplo n.º 1
0
def run():
    printLog("=====ZY_CreatTemp_V2====", 0)
    #Prompt user to open a image
    od = OpenDialog("Choose image file", None)
    if od is None:
        msgStr = "User Cancled"
        printLog(msgStr, 1)
    else:
        sourceFolder = od.getDirectory()
        fileName = od.getFileName()

        imp = IJ.openImage(sourceFolder + fileName)
        imp.show()
        n = imp.getNSlices()
        printLog("Processing source file: " + fileName, 1)
        imp2 = pickSlice(imp)
        if imp2:
            destFolder = os.path.join(sourceFolder, 'Temps')
            #outName = os.path.join(destFolder,fileName[:-4]+'_temp.tif') #remove the .tif in filename
            outName = os.path.join(destFolder, 'temp.tif')
            # check or make the folder
            if not os.path.isdir(destFolder):
                os.makedirs(destFolder)
            #make temp
            dupNSlice(imp2, n - 1)

            printLog("Saving to: " + outName, 1)
            fs = FileSaver(imp2)
            fs.saveAsTiffStack(outName)
            imp2.close()

    imp.close()
    msgStr = "ZY_CraetTemp_V2.py is Done."
    printLog(msgStr, 0)
Ejemplo n.º 2
0
def run():
	printLog("=====ZY_CreatTemp_V2====",0)
	#Prompt user to open a image
	od = OpenDialog("Choose image file", None)
	if od is None:
	 	msgStr = "User Cancled"
		printLog(msgStr,1)
	else:	
		sourceFolder = od.getDirectory()
		fileName = od.getFileName()


		imp = IJ.openImage(sourceFolder+fileName)
		imp.show()
		n = imp.getNSlices()
		printLog("Processing source file: " + fileName,1)
		imp2= pickSlice(imp)
		if imp2:
			destFolder = os.path.join(sourceFolder, 'Temps')
			#outName = os.path.join(destFolder,fileName[:-4]+'_temp.tif') #remove the .tif in filename
			outName = os.path.join(destFolder,'temp.tif')
			# check or make the folder
			if not os.path.isdir(destFolder):
				os.makedirs(destFolder)	
			#make temp
			dupNSlice(imp2,n-1)

			printLog("Saving to: " + outName,1)
	 		fs = FileSaver(imp2)
	 		fs.saveAsTiffStack(outName)
	 		imp2.close()
		
	imp.close()
	msgStr = "ZY_CraetTemp_V2.py is Done."
	printLog(msgStr,0)
	def exportTifStack(self, destFolder=''):
		channelNumber = 1
		for imp in self.channelImp:
			if not destFolder:
				destFolder = os.path.join(self.enclosingPath, self.enclosingfolder + '_tif')
			if not os.path.isdir(destFolder):
				os.makedirs(destFolder)
			
			if not imp:
				bPrintLog("ERROR: exportTifStack() did not find an imp at channel number '" + str(channelNumber) + "'", 0)
				return -1
				
			self.updateInfoStr()
			imp.setProperty("Info", self.infoStr);

			saveFile = os.path.splitext(self.filename)[0] + '_ch' + str(channelNumber) + '.tif'
			savePath = os.path.join(destFolder, saveFile)

			# save
			fs = FileSaver(imp)
			bPrintLog('saveTifStack():' + savePath, 3)
			if imp.getNSlices()>1:
				fs.saveAsTiffStack(savePath)
			else:
				fs.saveAsTiff(savePath)

			channelNumber += 1
Ejemplo n.º 4
0
def bSaveStack(imp, fullPath):
	fs = FileSaver(imp)
	#print 'bSaveStack()', fullPath, 'nslices=', imp.getNSlices()
	bPrintLog('bSaveStack():' + fullPath + ' slices=' + str(imp.getNSlices()), 1)
	if imp.getNSlices()>1:
		fs.saveAsTiffStack(fullPath)
	else:
		fs.saveAsTiff(fullPath)
Ejemplo n.º 5
0
def bSaveStack(imp, fullPath):
    fs = FileSaver(imp)
    #print 'bSaveStack()', fullPath, 'nslices=', imp.getNSlices()
    bPrintLog('bSaveStack():' + fullPath + ' slices=' + str(imp.getNSlices()),
              1)
    if imp.getNSlices() > 1:
        fs.saveAsTiffStack(fullPath)
    else:
        fs.saveAsTiff(fullPath)
Ejemplo n.º 6
0
def saveStack(destFolder,file_name,imp):	
	#rename the result and save it to subfolder
	if not os.path.isdir(destFolder):
		os.makedirs(destFolder)
	fullname=os.path.join(destFolder,file_name)
	#print (fullname)
	fs = FileSaver(imp)
	#print 'bSaveStack()', fullPath, 'nslices=', sr_imp.getNSlices()
	msgStr = "Dimension:" + str(imp.width) + " X " + str(imp.height) + " X " + str(imp.getNSlices())
	printLog("-Save "+file_name+" to "+destFolder,1)
	printLog("-"+msgStr,2)
	fs.saveAsTiffStack(fullname)
Ejemplo n.º 7
0
def saveStack(destFolder,file_name,imp):	
	#rename the result and save it to subfolder
	if not os.path.isdir(destFolder):
		os.makedirs(destFolder)
	fullname=os.path.join(destFolder,file_name)
	#print (fullname)
	fs = FileSaver(imp)
	#print 'bSaveStack()', fullPath, 'nslices=', sr_imp.getNSlices()
	msgStr = "Dimension:" + str(imp.width) + " X " + str(imp.height) + " X " + str(imp.getNSlices())
	printLog("-Save "+file_name+" to "+destFolder,1)
	printLog("-"+msgStr,2)
	fs.saveAsTiffStack(fullname)
Ejemplo n.º 8
0
def scaleandfilter(infile,outfile,scalex,scaley):
	
	print ("infile is: "+infile)
	
	imp = Opener().openImage(infile)
	print imp
	print "scalex = %f; scaley = %f" % (scalex,scaley)
	# Rescale
	ip = imp.getProcessor()
	ip.setInterpolate(True)
	sp = StackProcessor(imp.getStack(),ip);
	sp2=sp.resize(int(round(ip.width * scalex)), int(round(ip.height *scaley)));
	imp.setStack(imp.getTitle(),sp2);
	
	cal = imp.getCalibration()
	cal.pixelWidth /= scalex
	cal.pixelHeight /= scaley

	IJ.run(imp, "8-bit","")
	
	intif=infile+".tif"
	outtif=infile+"-filtered.tif"
	print("saving input file as "+intif)
	f=FileSaver(imp)
	f.saveAsTiffStack(intif)
	imp.close()

	# anisotropic filtering
	anisopts="-scanrange:10 -tau:2 -nsteps:2 -lambda:0.1 -ipflag:0 -anicoeff1:1 -anicoeff2:0 -anicoeff3:0"
	anisopts=anisopts+" -dx:%f -dy:%f -dz:%f" % (cal.pixelWidth,cal.pixelHeight,cal.pixelDepth)
	
	if sys.version_info > (2, 4):
		#for testing
		# subprocess.check_call(["cp",intif,outtif])
		subprocess.check_call(["anisofilter"]+anisopts.split(' ')+[intif,outtif])
	else:
		os.system(" ".join(["anisofilter"]+anisopts.split(' ')+[intif,outtif]))

	# Hessian (tubeness)
	print("Opening output tif: "+outtif)
	imp = Opener().openImage(outtif)
	imp.setCalibration(cal)
	print("Running tubeness on tif: "+outtif)
	IJ.run(imp,"Tubeness", "sigma=1")
	IJ.run(imp, "8-bit","")

	# Save to PIC
	print("Saving as PIC: "+outfile)
	# IJ.saveAs("tiff","outtif")
	IJ.run(imp,"Biorad ...", "biorad="+outfile)
Ejemplo n.º 9
0
    def savedata(imp, savepath, extension='ome.tiff', replace=False):

        # general function for saving image data in different formats

        # check if file already exists and delete if replace is true
        if os.path.exists(savepath):
            if replace:
                os.remove(savepath)
            if not replace:
                return None

        # general safety check
        # if not extension:
        #    extension = 'ome.tiff'

        # check extension
        if extension in ['tiff', 'tif', 'ome.tiff', 'ome.tif', 'png', 'jpeg']:

            fs = FileSaver(imp)
            nslices = imp.getStack().getSize()  # get the number of slices

            # in case of TIFF
            if extension == ('tiff' or 'tif' or 'TIFF' or 'TIF'):
                if nslices > 1:
                    fs.saveAsTiffStack(savepath)
                if nslices == 1:
                    fs.saveAsTiff(savepath)

            # in case of OME-TIFF
            elif extension == 'ome.tiff' or extension == 'ome.tif':
                pstr = ExportTools.bfexporter(imp, savepath, useLOCI=True)
                print('BioFormats Paramstring : ', pstr)

            # in case of PNG
            elif extension == ('png' or 'PNG'):
                fs.saveAsPng(savepath)

            # in case
            elif extension == ('jpeg' or 'jpg' or 'JPEG' or 'JPG'):
                fs.saveAsJpeg(savepath)

        else:
            extension = 'ome.tiff'
            print("save as OME-TIFF: ")  # savepath
            pstr = ExportTools.bfexporter(imp, savepath, useLOCI=True)
            print('BioFormats Paramstring : ', pstr)

        return savepath
Ejemplo n.º 10
0
def run():
	msg = "<html>"
	
	wm = WindowManager
	wcount = wm.getWindowCount()
	if wcount == 0:
		msg += "No windows open, nothing to do.<br/>"
		IJ.showMessage(PluginTitle, msg)
		return
	msg += "Number of open windows: " + str(wcount) + "<br/>"

	# let the User choose a directory to store the files
	target = DirectoryChooser("Choose target directory").getDirectory()
	if target is None:
		# User canceled the dialog
		msg += "<br/>No directory chosen, aborting.<br/>"
		IJ.showMessage(PluginTitle, msg)
		return
	msg += "Selected '" + target + "'as destination folder.<br/>"
	
	# determine padding width for filenames
	pad = len(str(wcount))

	for i in range(wcount):
		# image ID lists start with 1 instead of 0, so for convenience:
		wid = i + 1
		imp = wm.getImage(wid)
		imgid = wm.getNthImageID(wid)
		#print "window id:", wid, ", imageID:", wm.getNthImageID(wid)
		
		# Construct filename
		filename = 'tile_' + str(wid).zfill(pad) + '.tif'
		filepath = target + '/' + filename
		fs = FileSaver(imp)
		if imp.getImageStackSize() > 1:
			if not fs.saveAsTiffStack(filepath):
				IJ.error("<html>Error saving current image, stopping.")
				return
		else:
			if not fs.saveAsTiff(filepath):
				IJ.error("<html>Error saving current image, stopping.")
				return
	
	msg += "<br/>Successfully saved " + str(wcount) + " files.<br/>"
	IJ.showMessage(PluginTitle, msg)
Ejemplo n.º 11
0
    def saveTif(self, allowOverwrite=1):
        #make output folder
        if not os.path.isdir(self.dstFolder):
            os.makedirs(self.dstFolder)

        #ch1
        if self.imp_ch1:
            #savePath = self.dstFolder + self.enclosingFolderName + '_ch1.tif' #save into new folder
            if os.path.isfile(self.savePath_ch1) and not allowOverwrite:
                print bPrintLog('File Exists NOT Saving: ' + savePath, 3)
            else:
                fs = FileSaver(self.imp_ch1)
                bPrintLog('Saving: ' + self.savePath_ch1, 3)
                if self.imp_ch1.getNSlices() > 1:
                    fs.saveAsTiffStack(self.savePath_ch1)
                else:
                    fs.saveAsTiff(self.savePath_ch1)

        #ch2
        if self.imp_ch2:
            #save into new folder
            #savePath = self.dstFolder + self.enclosingFolderName + '_ch2.tif' #save into new folder
            if os.path.isfile(self.savePath_ch2) and not allowOverwrite:
                bPrintLog('File Exists NOT Saving: ' + self.savePath_ch2, 3)
            else:
                fs = FileSaver(self.imp_ch2)
                bPrintLog('Saving: ' + self.savePath_ch2, 3)
                if self.imp_ch2.getNSlices() > 1:
                    fs.saveAsTiffStack(self.savePath_ch2)
                else:
                    fs.saveAsTiff(self.savePath_ch2)

        #ch3
        if self.imp_ch3:
            #save into new folder
            #savePath = self.dstFolder + self.enclosingFolderName + '_ch3.tif' #save into new folder
            if os.path.isfile(self.savePath_ch3) and not allowOverwrite:
                bPrintLog('File Exists NOT Saving: ' + self.savePath_ch3, 3)
            else:
                fs = FileSaver(self.imp_ch3)
                bPrintLog('Saving: ' + self.savePath_ch3, 3)
                if self.imp_ch3.getNSlices() > 1:
                    fs.saveAsTiffStack(self.savePath_ch3)
                else:
                    fs.saveAsTiff(self.savePath_ch3)
Ejemplo n.º 12
0
	def saveTif(self, allowOverwrite=1):
		#make output folder
		if not os.path.isdir(self.dstFolder):
			os.makedirs(self.dstFolder)

		#ch1
		if self.imp_ch1:
			#savePath = self.dstFolder + self.enclosingFolderName + '_ch1.tif' #save into new folder
			if os.path.isfile(self.savePath_ch1) and not allowOverwrite:
				print bPrintLog('File Exists NOT Saving: ' + savePath, 3)
			else:
				fs = FileSaver(self.imp_ch1)
				bPrintLog('Saving: ' + self.savePath_ch1, 3)
				if self.imp_ch1.getNSlices()>1:
					fs.saveAsTiffStack(self.savePath_ch1)
				else:
					fs.saveAsTiff(self.savePath_ch1)
			
		#ch2
		if self.imp_ch2:
			#save into new folder
			#savePath = self.dstFolder + self.enclosingFolderName + '_ch2.tif' #save into new folder
			if os.path.isfile(self.savePath_ch2) and not allowOverwrite:
				bPrintLog('File Exists NOT Saving: ' + self.savePath_ch2, 3)
			else:
				fs = FileSaver(self.imp_ch2)
				bPrintLog('Saving: ' + self.savePath_ch2, 3)
				if self.imp_ch2.getNSlices()>1:
					fs.saveAsTiffStack(self.savePath_ch2)
				else:
					fs.saveAsTiff(self.savePath_ch2)
	
		#ch3
		if self.imp_ch3:
			#save into new folder
			#savePath = self.dstFolder + self.enclosingFolderName + '_ch3.tif' #save into new folder
			if os.path.isfile(self.savePath_ch3) and not allowOverwrite:
				bPrintLog('File Exists NOT Saving: ' + self.savePath_ch3, 3)
			else:
				fs = FileSaver(self.imp_ch3)
				bPrintLog('Saving: ' + self.savePath_ch3, 3)
				if self.imp_ch3.getNSlices()>1:
					fs.saveAsTiffStack(self.savePath_ch3)
				else:
					fs.saveAsTiff(self.savePath_ch3)
Ejemplo n.º 13
0
    def run(self):
        # make output folder
        if not os.path.isdir(self.dstFolder):
            os.makedirs(self.dstFolder)

        tifFileName = os.path.split(self.tifFilePath)[1]
        isCh1 = self.tifFilePath.endswith('_ch1.tif')
        isCh2 = self.tifFilePath.endswith('_ch2.tif')

        doThisFilePath = ''
        if self.alignmentChannel == 1 and isCh1:
            doThisFilePath = self.tifFilePath
        elif self.alignmentChannel == 2 and isCh2:
            doThisFilePath = self.tifFilePath

        if (doThisFilePath):
            ###
            ###
            bPrintLog('Loading file: ' + doThisFilePath, 3)
            imp = IJ.openImage(doThisFilePath)

            if imp is None:
                print "ERROR: could not open image from file:", doThisFilePath
                return -1

            d = imp.getDimensions(
            )  # Returns the dimensions of this image (width, height, nChannels, nSlices, nFrames) as a 5 element int array.
            logStr = 'dimensions are w:' + str(d[0]) + ' h:' + str(
                d[1]) + ' channels:' + str(d[2]) + ' slices:' + str(
                    d[3]) + ' frames:' + str(d[4])
            bPrintLog(logStr, 3)
            '''
			this is not designed to handle stacks that have frames !!!
			'''
            ##
            numSlices = imp.getNSlices()
            if numSlices > 1:
                pass
            else:
                numFrames = imp.getNFrames()

                if numFrames > 1:
                    # swap nFrames with nSLices
                    numSlices = numFrames
                    numFrames = 1
                    nChannels = 1

                    bPrintLog(
                        'Swapping frames for slices. numSlices=' +
                        str(numSlices) + ' numFrames=' + str(numFrames), 3)
                    imp.setDimensions(nChannels, numSlices, numFrames)
                else:
                    bPrintLog(
                        'ERROR: number of slices must be more than one, file: '
                        + tifFileName)
                    return -1
            ##

            # get the stack header (e.g. infoStr)
            infoStr = imp.getProperty("Info")  #get all tags
            if infoStr is None:
                infoStr = ''

            ## median filter
            if self.medianFilter > 0:
                bPrintLog('Running median filter: ' + str(self.medianFilter),
                          3)
                medianArgs = 'radius=' + str(self.medianFilter) + ' stack'
                IJ.run(imp, "Median...", medianArgs)
                infoStr += 'bMedianFilter=' + str(self.medianFilter) + '\n'
                imp.setProperty("Info", infoStr)

            #add to stack header
            infoStr += 'b_AlignFolder=v0.0\n'
            imp.setProperty("Info", infoStr)

            imp.show()
            impWin = imp.getTitle()

            #show the slice we start alignment on
            middleSlice = int(math.floor(numSlices / 2))
            imp.setSlice(middleSlice)

            transformationFile = self.dstFolder + tifFileName + '.txt'

            if run_alignment:
                bPrintLog('Running MultiStackReg for: ' + tifFileName, 3)
                stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' % (
                    impWin, transformationFile)
                IJ.run('MultiStackReg', stackRegParams)
            else:
                bPrintLog(
                    'DEBUG: NOT running MultiStackReg for: ' + tifFileName, 3)

            # save alignment
            bPrintLog('Saving aligned stack():' + self.dstFolder + tifFileName,
                      3)
            fs = FileSaver(imp)
            if numSlices > 1:
                fs.saveAsTiffStack(self.dstFolder + tifFileName)
            else:
                fs.saveAsTiff(self.dstFolder + tifFileName)

            imp.changes = 0
            imp.close()

            ###
            ###
            #open and run alignment on other channel
            if isCh1:
                otherFilePath = self.tifFilePath.strip('_ch1.tif') + '_ch2.tif'
            elif isCh2:
                otherFilePath = self.tifFilePath.strip('_ch2.tif') + '_ch1.tif'

            if os.path.isfile(otherFilePath):
                otherFileName = os.path.split(otherFilePath)[1]

                bPrintLog('Loading [OTHER] file: ' + doThisFilePath, 3)
                imp = IJ.openImage(otherFilePath)

                if imp is None:
                    print "ERROR: could not open other image from file:", otherFilePath
                    return -1

                ##
                numSlices = imp.getNSlices()
                if numSlices > 1:
                    pass
                else:
                    numFrames = imp.getNFrames()

                    if numFrames > 1:
                        # swap nFrames with nSLices
                        numSlices = numFrames
                        numFrames = 1
                        nChannels = 1

                        bPrintLog(
                            'Swapping frames for slices. numSlices=' +
                            str(numSlices) + ' numFrames=' + str(numFrames), 3)
                        imp.setDimensions(nChannels, numSlices, numFrames)
                    else:
                        bPrintLog(
                            'ERROR: number of slices must be more than one, file: '
                            + tifFileName)
                        return -1
                ##

                #add to stack header
                infoStr = imp.getProperty("Info")  #get all tags
                if infoStr is None:
                    infoStr = ''
                infoStr += 'b_AlignFolder=v0.0' + '\n'
                imp.setProperty("Info", infoStr)

                imp.show()
                impWin = imp.getTitle()

                if run_alignment:
                    bPrintLog('Running MultiStackReg for: ' + otherFileName, 3)
                    stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' % (
                        impWin, transformationFile)
                    IJ.run('MultiStackReg', stackRegParams)
                else:
                    bPrintLog(
                        'DEBUG: Not running MultiStackReg for: ' +
                        otherFileName, 3)

                #save alignment
                bPrintLog(
                    'Saving aligned stack():' + self.dstFolder + otherFileName,
                    3)
                fs = FileSaver(imp)
                if numSlices > 1:
                    fs.saveAsTiffStack(self.dstFolder + otherFileName)
                else:
                    fs.saveAsTiff(self.dstFolder + otherFileName)

                imp.changes = 0
                imp.close()
Ejemplo n.º 14
0
def run():
	print "===== bBatchConvertTo8Bitv3 ====="

	# Expecting one argument: the file path
	if len(sys.argv) < 2:
		print "   We need at least one folder as input"
		print "	  Usage: ./fiji-macosx bBatchConvertTo8Bitv3 <folder-path>/"

		# Prompt user for a folder
		sourceFolder = DirectoryChooser("Please Choose A Directory Of .tif Files").getDirectory()
		if not sourceFolder:
			return
	else:
		sourceFolder = sys.argv[1] #assuming it ends in '/'

	#get user options
	okGo = getOptions() # creates {numberOfChannels, replaceExisting}
	if okGo == -1:
		return 0

	destFolder = sourceFolder + "channels8_256/"

	#make destination directory
	if not os.path.isdir(destFolder):
		os.makedirs(destFolder)

	print "   Processing source folder: ", sourceFolder  
	print "   Saving to destination folder: ", destFolder  

	numOpened = 0
	numSaved = 0

	for filename in os.listdir(sourceFolder):	
		startWithDot = filename.startswith(".")
		isMax = filename.endswith("max.tif")
		isTif = filename.endswith(".tif")

		if (not startWithDot) and (not isMax) and (isTif):
			shortName, fileExtension = os.path.splitext(filename)
			outPath = destFolder + "/" + filename
			outPath1 = destFolder + "/" + shortName + "_ch1" + ".tif"
			outPath2 = destFolder + "/" + shortName + "_ch2" + ".tif"
			
			#before we open, check if eventual dest exists
			if not replaceExisting:
				if numberOfChannels == 2 and os.path.exists(outPath1) and os.path.exists(outPath2):
					print "   512 Destination file exists, not saving the image.", filename
					continue #with next iteration
				if numberOfChannels == 1 and os.path.exists(outPath):
					print "   512 Destination file exists, not saving the image.", filename
					continue #with next iteration
			
			print "   ===================================="
			print "   -> Opening", sourceFolder+filename  
			imp = IJ.openImage(sourceFolder + filename)
			if imp is None:  
				print "	     Could not open image from file:", filename  
				continue   #with next iteration
			
			imp.show()
			numOpened +=1
			
			#i can get properties as long list of {key=value}
			#how do i then set each property in new imp1/imp2? Do IJ.openImagehave ot loop?
			#print imp.getProperties()

			#in the future IJ.openImagehavewant to have option to scale down to 512X512
			#run("Scale...", "x=- y=- z=1.0 width=512 height=512 depth=196 interpolation=Bilinear average process create title=20131007_a144_008_ch1-1.tif");

			print "      Image is: " + str(imp.width) + " X " + str(imp.height) + " X " + str(imp.getNSlices())
			#if imp.getBitDepth() == 16:
			if imp.width>512 and imp.height>512:
				print "      Converting to 512X512 with 'Scale'"
				#IJ.run("8-bit")
				theTitle = "tmpOutput"
				IJ.run(imp, "Scale...", "x=- y=- z=1.0 width=512 height=512 depth=" + str(imp.getNSlices()) + " interpolate=Bilinear average process create title=" + theTitle)
				imp = IJ.getImage() 

				#bug: original window is left open
				
				if numberOfChannels == 2:
					print "      deinterleaving"
					IJ.run("Deinterleave", "how=2"); #makes 2 window
					
					#ch2
					imp2 = IJ.getImage()
					fs = FileSaver(imp2)
					print "      Saving 8bit File to", outPath2
					fs.saveAsTiffStack(outPath2)
					numSaved += 1
					imp2.changes = 0
					imp2.close()
					
					#ch1
					imp1 = IJ.getImage()
					fs = FileSaver(imp1)
					print "      Saving 8bit File to", outPath2
					fs.saveAsTiffStack(outPath1)
					numSaved += 1
					imp1.changes = 0
					imp1.close()
				elif numberOfChannels == 1: #single channel
					fs = FileSaver(imp)
					print "      Saving 8bit File to", outPath
					fs.saveAsTiffStack(outPath)
					numSaved += 1
					imp.changes = 0
					imp.close()

			else:
				print "   File was not larger than 512X512???"
			
			imp.close() #close original

		else:  
			if isTif:
				#print "   ===================================="
				print "   -> Ignoring .tif:", filename

	print "   ==="
	print "   bBatchConvertTo8Bitv3.py is Done, Number Opened " + str(numOpened) + ", Number Saved ", str(numSaved)
	print "   ==="
Ejemplo n.º 15
0
	def save(self, image, outputName):
		saver = FileSaver(image)
		saver.saveAsTiffStack(self.outputDir + self.subDir + outputName + ".tif")	
		print "Saved " + self.outputDir + self.subDir + outputName + ".tif"
Ejemplo n.º 16
0
def runOneTif(tifPath, dstTifPath):
    bPrintLog('=== runOneTif processing tif:' + tifPath, 3)

    bPrintLog('Loading file...', 3)
    imp = IJ.openImage(tifPath)

    if imp is None:
        bPrintLog('ERROR: could not open image from file:' + tifPath, 3)
        return 0

    logStr = 'done loading file: ' + str(imp.width) + ' ' + str(
        imp.height) + ' ' + str(imp.getNSlices())
    bPrintLog(logStr, 3)

    numSlices = imp.getNSlices()
    if numSlices > 1:
        pass
    else:
        bPrintLog('ERROR: number of slices must be more than one, file: ' +
                  tifPath)
        return 0
    bPrintLog('numSlices: ' + str(numSlices), 3)

    infoStr = imp.getProperty("Info")  #get all tags
    if infoStr is None:
        infoStr = ''
    infoStr += 'bMaxProject=v0.1\n'
    imp.setProperty("Info", infoStr)

    imp.show()
    impWin = imp.getTitle()

    # BODY

    madeMax = 0
    if numSlices == 1:
        # don;t make max
        madeMax = 0
        maxSlices = numSlices
        maxImp = imp
    else:
        madeMax = 1
        # take max project
        #IJ.run(imp, "Z Project...", "projection=[Max Intensity]");
        maxProjectArgs = 'projection=[Max Intensity]'
        IJ.run(imp, "Z Project...", maxProjectArgs)
        # makes a new window MAX_

        maxWindow = 'MAX_' + impWin
        maxImp = WindowManager.getImage(maxWindow)
        maxImp.setProperty("Info", infoStr)
        maxSlices = maxImp.getNSlices()  # should be 1

    # save
    bPrintLog('Saving stack with ' + str(maxSlices) + ' slices:' + dstTifPath,
              3)
    fs = FileSaver(maxImp)
    if maxSlices > 1:
        fs.saveAsTiffStack(dstTifPath)
    else:
        fs.saveAsTiff(dstTifPath)

    if madeMax:
        maxImp.changes = 0
        maxImp.close()

    # END BODY

    # close original
    imp.changes = 0
    imp.close()
Ejemplo n.º 17
0
def run():
	print "===== bBatchConvertTo8Bitv3 ====="

	global numberOfChannels
	global replaceExisting
	global gVersion

	gVersion = 3.1
	
	# Expecting one argument: the file path
	if len(sys.argv) < 2:
		print "   We need a hard-drive folder with .tif stacks as input"
		print "	  Usage: ./fiji-macosx bBatchConvertTo8Bitv3 <folder-path>/"

		# Prompt user for a folder
		sourceFolder = DirectoryChooser("Please Choose A Directory Of .tif Files").getDirectory()
		if not sourceFolder:
			return
	else:
		sourceFolder = sys.argv[1] #assuming it ends in '/'

	#get user options
	okGo = getOptions() # creates {numberOfChannels, replaceExisting}
	if okGo == -1:
		return 0

	destFolder = sourceFolder + "channels8/"
	destMaxFolder = sourceFolder + "max/"

	#make destination directory
	if not os.path.isdir(destFolder):
		os.makedirs(destFolder)

	#make max destination directory
	if not os.path.isdir(destMaxFolder):
		os.makedirs(destMaxFolder)
	
	print "   Processing source folder: ", sourceFolder  
	print "   Saving to destination folder: ", destFolder  
	IJ.log(" ")
	IJ.log("   ====== Starting bBatchConvertTo8Bit_v3 ======")
	IJ.log("   Processing from source folder: " + sourceFolder)
	IJ.log("   Saving to destination folder: " + destFolder)
	IJ.log("   gVersion=" + str(gVersion))
	IJ.log("   numberOfChannels=" + str(numberOfChannels))
	IJ.log("   replaceExisting=" + str(replaceExisting))
	
	numOpened = 0
	numSaved = 0

	for filename in os.listdir(sourceFolder):	
		startWithDot = filename.startswith(".")
		isMax = filename.endswith("max.tif")
		isTif = filename.endswith(".tif")

		if (not startWithDot) and (not isMax) and (isTif):
			shortName, fileExtension = os.path.splitext(filename)
			outPath = destFolder + "/" + filename
			outPath1 = destFolder + "/" + shortName + "_ch1" + ".tif"
			outPath2 = destFolder + "/" + shortName + "_ch2" + ".tif"

			#max projection output
			outMaxPath = destMaxFolder + "/" + "max_" + filename
			outMaxPath1 = destMaxFolder + "/" + "max_" + shortName + "_ch1" + ".tif"
			outMaxPath2 = destMaxFolder + "/" + "max_" + shortName + "_ch2" + ".tif"
			
			#before we open, check if eventual dest exists
			if not replaceExisting:
				if numberOfChannels == 2 and os.path.exists(outPath1) and os.path.exists(outPath2):
					msgStr = "   8-Bit Destination file exists, not processing the image:" + filename
					print msgStr
					IJ.log(msgStr)
					continue #with next iteration
				if numberOfChannels == 1 and os.path.exists(outPath):
					msgStr = "   8-Bit Destination file exists, not processing the image:" + filename
					print msgStr
					IJ.log(msgStr)
					continue #with next iteration
			
			print "   ===================================="
			msgStr = "   -->> Opening " + sourceFolder+filename  
			print msgStr
			IJ.log(msgStr)
			imp = IJ.openImage(sourceFolder + filename)
			if imp is None:  
				msgStr = "	     ERROR: Could not open image from file: " + filename  
				print msgStr
				IJ.log(msgStr)
				continue   #with next iteration
			
			imp.show()
			numOpened +=1

			infoStr = imp.getProperty("Info") #get all .tif tags
			if not infoStr:
				infoStr = ''
			infoStr += 'bBatchConvertTo8Bit_Version=' + str(gVersion) + '\n'
			infoStr += 'bBatchConvertTo8Bit_Time=' + time.strftime("%Y%m%d") + '_' + time.strftime("%H%M%S") + '\n'
			
			msgStr = "      Original Image is: " + str(imp.width) + " X " + str(imp.height) + " X " + str(imp.getNSlices())
			print msgStr
			IJ.log(msgStr)
			if imp.getBitDepth() == 16:
				msgStr = "      Converting to 8-bit..."
				print msgStr
				IJ.log(msgStr)
				IJ.run("8-bit")

				if numberOfChannels == 2:
					msgStr = "      deinterleaving"
					print msgStr
					IJ.run("Deinterleave", "how=2"); #makes 2 window
					
					#
					#ch2
					imp2 = IJ.getImage()
					imp2.setProperty("Info", infoStr);
					fs = FileSaver(imp2)
					msgStr = "      ch2: Saving deinterleaved 8bit File to: " + outPath2
					print msgStr
					IJ.log(msgStr)

					numSlices = imp2.getNSlices() 
					if (numSlices>1):
						fs.saveAsTiffStack(outPath2)
					else:
						fs.saveAsTiff(outPath2)
						
					#max, ch2
					if (numSlices>1):
						maxCmdParams = 'start=1' + ' stop=' + str(numSlices) + ' projection=[Max Intensity]'
						IJ.run("Z Project...", maxCmdParams)
						#impMax2 = IJ.getImage()
						
					print "      Saving 8bit Max File to", outMaxPath2
					impMax2 = IJ.getImage()
					fs = FileSaver(impMax2)
					fs.saveAsTiff(outMaxPath2)
					
					impMax2.changes = 0
					impMax2.close()
					
					numSaved += 1
					imp2.changes = 0
					imp2.close()
					
					#
					#ch1
					imp1 = IJ.getImage()
					imp1.setProperty("Info", infoStr);
					fs = FileSaver(imp1)
					msgStr = "      ch1: Saving deinterleaved 8bit File to" + outPath1
					print msgStr
					
					numSlices = imp1.getNSlices() 
					if (numSlices>1):
						fs.saveAsTiffStack(outPath1)
					else:
						fs.saveAsTiff(outPath1)

					#max, ch1
					if (numSlices>1):
						maxCmdParams = 'start=1' + ' stop=' + str(numSlices) + ' projection=[Max Intensity]'
						IJ.run("Z Project...", maxCmdParams)
					
					impMax1 = IJ.getImage()
					fs = FileSaver(impMax1)
					msgStr = "      Saving 8bit Max File to" + outMaxPath1
					print msgStr
					IJ.log(msgStr)
					fs.saveAsTiff(outMaxPath1)
					impMax1.changes = 0
					impMax1.close()

					numSaved += 1
					imp1.changes = 0
					imp1.close()
				
				elif numberOfChannels == 1: #single channel
					imp.setProperty("Info", infoStr);
					
					fs = FileSaver(imp)
					msgStr = "      Saving 8bit File to" + outPath
					print msgStr
					IJ.log(msgStr)
					
					numSlices = imp.getNSlices() 

					if (numSlices>1):
						fs.saveAsTiffStack(outPath)
					else:
						fs.saveAsTiff(outPath)
					numSaved += 1

					#max
					if (numSlices>1):
						maxCmdParams = 'start=1' + ' stop=' + str(numSlices) + ' projection=[Max Intensity]'
						IJ.run("Z Project...", maxCmdParams)
					
					impMax = IJ.getImage()
					fs = FileSaver(impMax)
					print "      Saving 8bit Max File to", outMaxPath
					fs.saveAsTiff(outMaxPath)
					impMax.changes = 0
					impMax.close()

					imp.changes = 0
					imp.close()

			else:
				print "   File was not 16 bit???"
			
			imp.close() #close original

		else:  
			if (not startWithDot) and isTif:
				#print "   ===================================="
				print filename
				msgStr = "   -> Ignoring .tif:" + filename
				print msgStr
				IJ.log(msgStr)

	msgStr = "   ====== bBatchConvertTo8Bitv3.py is Done ======"
	print msgStr
	IJ.log(msgStr)
	msgStr = "   Total Number Opened " + str(numOpened) + ", Total Number Saved " + str(numSaved)
	print msgStr
	IJ.log(msgStr)
def run():
	print "===== bBatchConvertTo8Bitv3 ====="

	# Expecting one argument: the file path
	if len(sys.argv) < 2:
		print "   We need a hard-drive folder with .tif stacks as input"
		print "	  Usage: ./fiji-macosx bBatchConvertTo8Bitv3 <folder-path>/"

		# Prompt user for a folder
		sourceFolder = DirectoryChooser("Please Choose A Directory Of .tif Files").getDirectory()
		if not sourceFolder:
			return
	else:
		sourceFolder = sys.argv[1] #assuming it ends in '/'

	#get user options
	okGo = getOptions() # creates {numberOfChannels, replaceExisting}
	if okGo == -1:
		return 0

	destFolder = sourceFolder + "channels8/"
	destMaxFolder = sourceFolder + "max/"

	#make destination directory
	if not os.path.isdir(destFolder):
		os.makedirs(destFolder)

	#make max destination directory
	if not os.path.isdir(destMaxFolder):
		os.makedirs(destMaxFolder)
	
	print "   Processing source folder: ", sourceFolder  
	print "   Saving to destination folder: ", destFolder  
	IJ.log("   ====== Startin bBatchConvertTo8Bitv3 ======")
	IJ.log("   Processing source folder: " + sourceFolder)
	IJ.log("   Saving to destination folder: " + destFolder)

	numOpened = 0
	numSaved = 0

	for filename in os.listdir(sourceFolder):	
		startWithDot = filename.startswith(".")
		isMax = filename.endswith("max.tif")
		isTif = filename.endswith(".tif")

		if (not startWithDot) and (not isMax) and (isTif):
			shortName, fileExtension = os.path.splitext(filename)
			outPath = destFolder + "/" + filename
			outPath1 = destFolder + "/" + shortName + "_ch1" + ".tif"
			outPath2 = destFolder + "/" + shortName + "_ch2" + ".tif"

			#max projection output
			outMaxPath = destMaxFolder + "/" + "max_" + filename
			outMaxPath1 = destMaxFolder + "/" + "max_" + shortName + "_ch1" + ".tif"
			outMaxPath2 = destMaxFolder + "/" + "max_" + shortName + "_ch2" + ".tif"
			
			#before we open, check if eventual dest exists
			if not replaceExisting:
				if numberOfChannels == 2 and os.path.exists(outPath1) and os.path.exists(outPath2):
					msgStr = "   8-Bit Destination file exists, not processing the image:" + filename
					print msgStr
					IJ.log(msgStr)
					continue #with next iteration
				if numberOfChannels == 1 and os.path.exists(outPath):
					msgStr = "   8-Bit Destination file exists, not processing the image:" + filename
					print msgStr
					IJ.log(msgStr)
					continue #with next iteration
			
			print "   ===================================="
			msgStr = "   -> Opening " + sourceFolder+filename  
			print msgStr
			IJ.log(msgStr)
			imp = IJ.openImage(sourceFolder + filename)
			if imp is None:  
				msgStr = "	     ERROR: Could not open image from file: " + filename  
				print msgStr
				IJ.log(msgStr)
				continue   #with next iteration
			
			imp.show()
			numOpened +=1
			
			#i can't get properties as long list of {key=value}
			#how do i then set each property in new imp1/imp2? Do IJ.openImagehave ot loop?
			#infoProperty = imp.getInfoProperty() #Returns the "Info" property string, java.lang.String
			#print 'infoProperty'
			#print infoProperty

			#.getProp(key) #Returns the value from the "Info" property string associated with 'key'
			
			#myProp = imp.getProperties() #returns java.util.Properties
			#print 'myProp (really long)'
			#print myProp

			#print 'patrick'
			#myList = str(myProp).split('\r')
			
			#I want' to strip out 'Info=ImageDescription: '
			#myList = re.sub('Info=ImageDescription: ', '', str(myList))
			
			#for i in range (0,len(myList)):
			#	myList[i] = myList[i].split('=')
			
			#print myList[0]
			#print myList[1]
			#print myList[2]
			#print myList[3]

			#imp.setProperty('myStr', 1)

			#try usinf ImageStack
			#myImageStack = imp.getImageStack()
			
			#eventuallly just call imp.getProp(str) which Returns the value from the "Info"
			
			#in the future IJ.openImagehavewant to have option to scale down to 512X512
			#run("Scale...", "x=- y=- z=1.0 width=512 height=512 depth=196 interpolation=Bilinear average process create title=20131007_a144_008_ch1-1.tif");

			msgStr = "      Original Image is: " + str(imp.width) + " X " + str(imp.height) + " X " + str(imp.getNSlices())
			print msgStr
			IJ.log(msgStr)
			if imp.getBitDepth() == 16:
				msgStr = "      Converting to 8-bit..."
				print msgStr
				IJ.log(msgStr)
				IJ.run("8-bit")

				if numberOfChannels == 2:
					msgStr = "      deinterleaving"
					print msgStr
					IJ.run("Deinterleave", "how=2"); #makes 2 window
					
					#
					#ch2
					imp2 = IJ.getImage()
					fs = FileSaver(imp2)
					msgStr = "      ch2: Saving deinterleaved 8bit File to: " + outPath2
					print msgStr
					IJ.log(msgStr)

					numSlices = imp2.getNSlices() 
					if (numSlices>1):
						fs.saveAsTiffStack(outPath2)
					else:
						fs.saveAsTiff(outPath2)
						
					#max, ch2
					if (numSlices>1):
						maxCmdParams = 'start=1' + ' stop=' + str(numSlices) + ' projection=[Max Intensity]'
						IJ.run("Z Project...", maxCmdParams)
						#impMax2 = IJ.getImage()
						
					print "      Saving 8bit Max File to", outMaxPath2
					impMax2 = IJ.getImage()
					fs = FileSaver(impMax2)
					fs.saveAsTiff(outMaxPath2)
					
					impMax2.changes = 0
					impMax2.close()
					
					numSaved += 1
					imp2.changes = 0
					imp2.close()
					
					#
					#ch1
					imp1 = IJ.getImage()
					fs = FileSaver(imp1)
					msgStr = "      ch1: Saving deinterleaved 8bit File to" + outPath1
					print msgStr
					
					numSlices = imp1.getNSlices() 
					if (numSlices>1):
						fs.saveAsTiffStack(outPath1)
					else:
						fs.saveAsTiff(outPath1)

					#max, ch1
					if (numSlices>1):
						maxCmdParams = 'start=1' + ' stop=' + str(numSlices) + ' projection=[Max Intensity]'
						IJ.run("Z Project...", maxCmdParams)
					
					impMax1 = IJ.getImage()
					fs = FileSaver(impMax1)
					msgStr = "      Saving 8bit Max File to" + outMaxPath1
					print msgStr
					IJ.log(msgStr)
					fs.saveAsTiff(outMaxPath1)
					impMax1.changes = 0
					impMax1.close()

					numSaved += 1
					imp1.changes = 0
					imp1.close()
				
				elif numberOfChannels == 1: #single channel
					fs = FileSaver(imp)
					msgStr = "      Saving 8bit File to" + outPath
					print msgStr
					IJ.log(msgStr)
					
					numSlices = imp.getNSlices() 

					if (numSlices>1):
						fs.saveAsTiffStack(outPath)
					else:
						fs.saveAsTiff(outPath)
					numSaved += 1

					#max
					if (numSlices>1):
						maxCmdParams = 'start=1' + ' stop=' + str(numSlices) + ' projection=[Max Intensity]'
						IJ.run("Z Project...", maxCmdParams)
					
					impMax = IJ.getImage()
					fs = FileSaver(impMax)
					print "      Saving 8bit Max File to", outMaxPath
					fs.saveAsTiff(outMaxPath)
					impMax.changes = 0
					impMax.close()

					imp.changes = 0
					imp.close()

			else:
				print "   File was not 16 bit???"
			
			imp.close() #close original

		else:  
			if (not startWithDot) and isTif:
				#print "   ===================================="
				print filename
				msgStr = "   -> Ignoring .tif:" + filename
				print msgStr
				IJ.log(msgStr)

	msgStr = "   bBatchConvertTo8Bitv3.py is Done, Number Opened " + str(numOpened) + ", Number Saved " + str(numSaved)
	print "   ==="
	print msgStr
	print "   ==="
	IJ.log(msgStr)
Ejemplo n.º 19
0
	def saveMultichannelImage(self, title, channels, luts):
		tmp = RGBStackMerge.mergeChannels(channels, False)
		tmp.luts = luts
		saver = FileSaver(tmp)
		saver.saveAsTiffStack(self.outputDir + title + ".tif")
		tmp.close()
Ejemplo n.º 20
0
def runOneTif(tifPath, dstTifPath):
	bPrintLog('=== runOneTif processing tif:' + tifPath, 3)

	bPrintLog('Loading file...', 3)
	imp = IJ.openImage(tifPath)  

	if imp is None:  
		bPrintLog('ERROR: could not open image from file:' + tifPath, 3)
		return 0  

	logStr = 'done loading file: ' + str(imp.width) + ' ' + str(imp.height) + ' ' + str(imp.getNSlices())
	bPrintLog(logStr, 3)

	numSlices = imp.getNSlices()
	if numSlices>1:
		pass
	else:
		bPrintLog('ERROR: number of slices must be more than one, file: ' + tifPath)
		return 0
	bPrintLog('numSlices: ' + str(numSlices), 3)
	
	infoStr = imp.getProperty("Info") #get all tags
	if infoStr is None:
		infoStr = ''
	infoStr += 'bMaxProject=v0.1\n'
	imp.setProperty("Info", infoStr)

	imp.show()
	impWin = imp.getTitle()

	# BODY
	
	madeMax = 0
	if numSlices == 1:
		# don;t make max
		madeMax = 0
		maxSlices = numSlices
		maxImp = imp
	else:
		madeMax = 1
		# take max project
		#IJ.run(imp, "Z Project...", "projection=[Max Intensity]");
		maxProjectArgs = 'projection=[Max Intensity]'
		IJ.run(imp, "Z Project...", maxProjectArgs); # makes a new window MAX_
		
		maxWindow = 'MAX_' + impWin
		maxImp = WindowManager.getImage(maxWindow)
		maxImp.setProperty("Info", infoStr)
		maxSlices = maxImp.getNSlices() # should be 1
	
	# save
	bPrintLog('Saving stack with ' + str(maxSlices) + ' slices:' + dstTifPath, 3)
	fs = FileSaver(maxImp)
	if maxSlices>1:
		fs.saveAsTiffStack(dstTifPath)
	else:
		fs.saveAsTiff(dstTifPath)

	if madeMax:
		maxImp.changes = 0
		maxImp.close()

	# END BODY
	
	# close original
	imp.changes = 0
	imp.close()
Ejemplo n.º 21
0
    projectR.doProjection()
    projectionR = projectR.getProjection()

    impR2 = ImageCalculator().run("Subtract create stack", impR1, projectionR)
    IJ.run(impR2, "Enhance Contrast", "saturated=0.4 process_all")
    IJ.run(impR2, "Set Scale...",
           "distance=" + str(CamRScale) + " known=1 unit=cm")
    IJ.run(impR2, "Grid...",
           "grid=Lines area=" + str(GridSize) + " color=Cyan")
    IJ.run(impR2, "Translate...",
           "x=" + str(TranslateR) + " y=0 interpolation=None stack")

    savepath = path.join(folder, UID + "_CR.tif")
    print savepath
    fs = FileSaver(impR2)
    if fs.saveAsTiffStack(savepath):
        print("Files saved succesfully")
else:
    print "No CamR Images to Open"

if runCamL:
    impL1 = FolderOpener.open(folder, "file=CamL sort")
    UID = impL1.title
    filepath = folder.strip(UID + '/')

    projectL = ZProjector(impL1)
    projectL.setMethod(ZProjector.AVG_METHOD)
    projectL.setImage(impL1)
    projectL.setStartSlice(int(BackgroundWindowStart))
    projectL.setStopSlice(int(BackgroundWindowEnd))
    projectL.doProjection()
Ejemplo n.º 22
0
def run():
    print "=====ZY_Resizetif_V1===="

    #expecting one argument: the file path (choose the folder first)
    if len(sys.argv) < 2:
        print "We need at least one folder as input"
        print "Please choose the input folder"

        #prompt user to choose a folder"
        sourceFolder = DirectoryChooser(
            "Please choose a directory of .tif files").getDirectory()
        if not sourceFolder:
            return
    else:
        sourceFolder = sys.argv[1]  #assuming it ends in '/'

    #get user options

    okGo = getOptions()
    if okGo == -1:
        return 0
    destFolder = os.path.join(sourceFolder, 'resized')

    print destFolder

    # check or make the folder
    if not os.path.isdir(destFolder):
        os.makedirs(destFolder)

    print "Processing souce folder", sourceFolder
    print "Saving to destination folder", destFolder
    IJ.log("   ====== Startin ZY_resize_V1 ======")
    IJ.log("   Processing source folder: " + sourceFolder)
    IJ.log("   Saving to destination folder: " + destFolder)

    numOpened = 0
    numSaved = 0

    for filename in os.listdir(sourceFolder):
        startWithDot = filename.startswith(".")
        isMax = filename.endswith("max.tif")
        isTif = filename.endswith(".tif")

        if (not startWithDot) and (not isMax) and isTif:
            shortname, fileExtension = os.path.splitext(filename)
            outPath = destFolder + "/" + filename
            outPath1 = destFolder + "/" + shortname + "_ch1" + ".tif"
            outPath2 = destFolder + "/" + shortname + "_ch2" + ".tif"

            # before processing, check if eventual dest exists
            if not replaceExisting:
                if numberOfChannels == 2 and os.path.exists(
                        outPath1) and os.path.exists(outPath2):
                    msgStr = "        -->The file==" + filename + "== has been resized, not processing again"
                    print msgStr
                    IJ.log(msgStr)
                    continue  #with next iteration
                if numberOfChannels == 1 and os.path.exists(outPath):
                    msgStr = "        -->The file==" + filename + "== has been resized, not processing again"
                    print msgStr
                    IJ.log(msgStr)
                    continue  #with next iteration

            print "================================"
            msgStr = str(numOpened +
                         1) + ". opening>> " + sourceFolder + filename
            print msgStr
            IJ.log(msgStr)

            imp = IJ.openImage(sourceFolder + filename)
            if imp is None:
                msgStr = "        -->>Error: could not open image file:" + filename
                print msgStr
                IJ.log(msgStr)
                continue  #with next iteration

            imp.show()
            numOpened += 1

            msgStr = "        -->Original size is:" + str(
                imp.width) + "x" + str(imp.height) + "x" + str(
                    imp.getNSlices())
            print msgStr
            IJ.log(msgStr)

            if imp.width < reWidth or imp.height < reHeight:
                IJ.run(
                    imp, "Size...", "width=" + str(reWidth) + " height=" +
                    str(reHeight) + " depth=" + str(imp.getNSlices()) +
                    " interpolation=Bilinear")
                msgStr = "        -> Changing size to:" + str(
                    imp.width) + "x" + str(imp.height) + "x" + str(
                        imp.getNSlices())
                print msgStr
                IJ.log(msgStr)

                imp = IJ.getImage()

                if numberOfChannels == 2:
                    print "deinterleaving"
                    IJ.run("Deinterleaving", "how = 2")  #make 2 windows

                    #ch2
                    imp2 = IJ.getImage()
                    fs = FileSaver(imp2)
                    print "saving channel 2 file to", outPath2
                    fs.saveAsTiffStack(outPath2)
                    numSaved += 1
                    imp2.changes = 0
                    imp2.close()

                    #ch1
                    imp1 = IJ.getImage()
                    fs = FileSaver(imp1)
                    print "saving channel 1 file to", outPath1
                    fs.saveAsTiffStack(outPath1)
                    numSaved += 1
                    imp1.changes = 0
                    imp1.close()

                elif numberOfChannels == 1:
                    fs = FileSaver(imp)
                    print "saving file to", outPath
                    fs.saveAsTiffStack(outPath)
                    numSaved += 1
                    imp.changes = 0
            else:
                msgStr = "        --> The file == " + filename + "== was ignored,because the size is bigger than setting"
                print msgStr
                IJ.log(msgStr)

            imp.close()  #close original

        else:  # showing that we ignoring the max

            if (not startWithDot) and isTif:
                #print "   ===================================="
                print filename
                msgStr = "        --> Ignoring .tif:" + filename
                print msgStr
                IJ.log(msgStr)

    msgStr = "   ZY_Resized_V1.py is Done, Number Opened " + str(
        numOpened) + ", Number Saved " + str(numSaved)
    print "   ==="
    print msgStr
    print "   ==="
    IJ.log("==========")
    IJ.log(msgStr)
Ejemplo n.º 23
0
#    return filedir
  return target_folder

filedir = getArg()   
filedir = os.path.join(filedir)
filelist = os.listdir(filedir)
for afile in filelist:
  if afile.lower().endswith('.lif'):
    print filedir
    print "..." + afile
    filebase = splitext(afile)[0]
    imps = getImps(os.path.join(filedir, afile))
    printInfo(imps)	
    for (counter, item) in enumerate(imps):
      outimp = zproj(item)
      #outname = filedir + filebase + "/" + "s" + str(counter) + ".tif"
      subname = ijtool.split(item.getTitle(), " - ")[1]
      #outname = filedir + filebase + "/" + subname + "_ZP.tif"
      outname = os.path.join(filedir, filebase, subname + "_ZP.tif")
      print outname
      outdir = os.path.join(filedir, filebase)
      print outdir
      if not os.path.isdir(outdir):
        os.mkdir(outdir)
      fs = FileSaver(outimp)
      fs.saveAsTiffStack(outname)

#outimp = zproject(filepath)
#outimp.show()

Ejemplo n.º 24
0
def PrepareDatabase(minw, maxw, baseDir, aspectRatio, majorWidth, majorHeight):
    outputpath = baseDir + "/" + str(majorWidth) + "_" + str(
        majorHeight) + "_orig.tif"
    #initialize stacks and labels
    stackScaled = []
    stackOrig = ImageStack(majorWidth, majorHeight)
    imageNames = []
    for i in range(minw, maxw + 1):
        stackScaled.append(ImageStack(i, int(round(i / aspectRatio, 0))))
        imageNames.append('')

    counter = 0

    # initialize zip file for originals
    zf = zipfile.ZipFile(baseDir + "/originals.zip",
                         mode='w',
                         compression=zipfile.ZIP_DEFLATED,
                         allowZip64=1)
    zf.writestr('from_string.txt', 'hello')
    zf.close()
    zf = zipfile.ZipFile(baseDir + "/originals.zip",
                         mode='a',
                         compression=zipfile.ZIP_DEFLATED,
                         allowZip64=1)

    for root, dirs, files in os.walk(str(baseDir)):
        for f1 in files:
            if f1.endswith(".jpg") or f1.endswith(".jpe") or f1.endswith(
                    ".jpeg"):
                id = root + "/" + f1
                IJ.redirectErrorMessages()
                IJ.redirectErrorMessages(1)
                imp = IJ.openImage(id)
                if imp is None:
                    print "Couldn\'t open image from file:", id
                    continue
                # skip non RGBimages
                if imp.getProcessor().getNChannels() != 3:
                    print "Converting non RGB image:", id
                    if imp.getStackSize() > 1:
                        StackConverter(imp).convertToRGB()
                    else:
                        ImageConverter(imp).convertToRGB()
                #skip images with different aspect ratio
                width = imp.getWidth()
                height = imp.getHeight()
                ratio = round(
                    float(width) / float(height), 2
                )  # this makes the ratio filering approximate, minor variations in image dimensions will be ignored
                if ratio != aspectRatio:
                    IJ.log("Skipping image of size: " + str(width) + "," +
                           str(height))
                    continue
                # now scale the image within a given range
                scale = Scale(imp.getProcessor())
                IJ.log("Scaling image " + str(counter) + " " + str(id))
                for i in range(minw, maxw + 1):
                    stackScaled[i - minw].addSlice(
                        None,
                        ScaleImageToSize(scale, i,
                                         int(round(i / aspectRatio, 0))))
                    imageNames[i - minw] += str(id) + ";"
                # save the originals to a temp directory
                scaledOrig = ImagePlus(
                    None, ScaleImageToSize(scale, majorWidth, majorHeight))
                SaveToZip(zf, scaledOrig, baseDir, counter)
                counter += 1
    zf.close()
    # save the stacks
    for i in range(minw, maxw + 1):
        impScaled = ImagePlus(
            str(minw) + "_" + str(int(round(i / aspectRatio, 0))),
            stackScaled[i - minw])
        impScaled.show()
        #print imageNames
        impScaled.setProperty('Info', imageNames[i - minw][:-1])
        fs = FileSaver(impScaled)
        filepath = baseDir + "/" + str(i) + "_" + str(
            int(round(i / aspectRatio, 0))) + ".tif"
        IJ.log("Saving output stack" + str(filepath))
        fs.saveAsTiffStack(filepath)
        #IJ.save(impScaled, filepath);
        IJ.log("Done")
Ejemplo n.º 25
0
def run():
	print "=====ZY_Resizetif_V1===="

	#expecting one argument: the file path (choose the folder first)
	if len(sys.argv) < 2:
		print "We need at least one folder as input"
		print "Please choose the input folder"

		#prompt user to choose a folder"
		sourceFolder = DirectoryChooser("Please choose a directory of .tif files").getDirectory()
		if not sourceFolder:
			return
	else:
		sourceFolder = sys.argv[1] #assuming it ends in '/'

	#get user options

	okGo = getOptions()
	if okGo == -1:
		return 0
	destFolder = os.path.join(sourceFolder, 'resized')
	
	print destFolder
		
	# check or make the folder
	if not os.path.isdir(destFolder):
		os.makedirs(destFolder)

	print "Processing souce folder", sourceFolder
	print "Saving to destination folder", destFolder
	IJ.log("   ====== Startin ZY_resize_V1 ======")
	IJ.log("   Processing source folder: " + sourceFolder)
	IJ.log("   Saving to destination folder: " + destFolder)
	
	numOpened = 0
	numSaved = 0

	for filename in os.listdir(sourceFolder):
		startWithDot = filename.startswith(".")
	 	isMax = filename.endswith("max.tif")
	 	isTif = filename.endswith(".tif")

	 	if (not startWithDot) and (not isMax) and isTif:
	 		shortname, fileExtension = os.path.splitext(filename)
	 		outPath = destFolder + "/" + filename
	 		outPath1 = destFolder + "/" + shortname + "_ch1" + ".tif"
	 		outPath2 = destFolder + "/" + shortname + "_ch2" + ".tif"

	 		# before processing, check if eventual dest exists
	 		if not replaceExisting:
	 			if numberOfChannels == 2 and os.path.exists(outPath1) and os.path.exists(outPath2):
	 				msgStr = "        -->The file==" + filename + "== has been resized, not processing again"
	 				print msgStr
	 				IJ.log(msgStr)
	 				continue #with next iteration
	 			if numberOfChannels == 1 and os.path.exists(outPath):
	 				msgStr = "        -->The file==" + filename + "== has been resized, not processing again"
	 				print msgStr
	 				IJ.log(msgStr)
	 				continue #with next iteration
	 		
	 		print "================================"
	 		msgStr = str(numOpened+1) + ". opening>> " + sourceFolder + filename
	 		print msgStr
	 		IJ.log(msgStr)

	 		imp = IJ.openImage(sourceFolder+filename)
	 		if imp is None:
	 			msgStr = "        -->>Error: could not open image file:" + filename
	 			print msgStr
	 			IJ.log(msgStr)
				continue #with next iteration

			imp.show()
			numOpened +=1
 
			msgStr = "        -->Original size is:" + str(imp.width) + "x" + str(imp.height) + "x" + str(imp.getNSlices())
			print msgStr
	 		IJ.log(msgStr)

	 		if imp.width < reWidth or imp.height < reHeight:
	 			IJ.run(imp, "Size...", "width=" + str(reWidth) + " height=" + str(reHeight) + " depth=" + str(imp.getNSlices()) + " interpolation=Bilinear")
				msgStr = "        -> Changing size to:" + str(imp.width) + "x" + str(imp.height)+ "x" + str(imp.getNSlices())
	 			print msgStr
	 			IJ.log(msgStr)
				
				imp = IJ.getImage() 	

	 			if numberOfChannels == 2:
	 				print "deinterleaving"
	 				IJ.run("Deinterleaving", "how = 2") #make 2 windows

	 				#ch2
	 				imp2=IJ.getImage()
	 				fs = FileSaver(imp2)
	 				print "saving channel 2 file to", outPath2
	 				fs.saveAsTiffStack(outPath2)
	 				numSaved += 1
	 				imp2.changes = 0
	 				imp2.close()

	 				#ch1
	 				imp1 = IJ.getImage()
	 				fs= FileSaver(imp1)
	 				print "saving channel 1 file to", outPath1
	 				fs.saveAsTiffStack(outPath1)
	 				numSaved += 1
	 				imp1.changes = 0
	 				imp1.close()
	 			
	 			elif numberOfChannels == 1:
	 				fs= FileSaver(imp)
	 				print "saving file to", outPath
	 				fs.saveAsTiffStack(outPath)
	 				numSaved += 1
	 				imp.changes = 0
	 		else:
	 			msgStr = "        --> The file == " + filename + "== was ignored,because the size is bigger than setting"
				print msgStr
				IJ.log(msgStr)
	 		
	 		imp.close() #close original
	 			
		else: # showing that we ignoring the max

			if (not startWithDot) and isTif:
				#print "   ===================================="
				print filename
				msgStr = "        --> Ignoring .tif:" + filename
				print msgStr
				IJ.log(msgStr)	

	msgStr = "   ZY_Resized_V1.py is Done, Number Opened " + str(numOpened) + ", Number Saved " + str(numSaved)
	print "   ==="
	print msgStr
	print "   ==="
	IJ.log("==========")
	IJ.log(msgStr)
def scaleandfilter(infile,outfile,scalex,scaley,scalez,anisofilter,runtube):
	
	print ("infile is: "+infile)
	imp = Opener().openImage(infile)
	print imp
	print "scalex = %f; scaley = %f ; scalez = %f" % (scalex,scaley,scalez)
	
	# Rescale
	cal = imp.getCalibration()
	iml = ImgLib.wrap(imp)
	scaledimg = Scale3D(iml, scalex, scaley, scalez)
	imp2=ImgLib.wrap(scaledimg)
	
	# find range of pixel values for scaled image
	from mpicbg.imglib.algorithm.math import ComputeMinMax
	# (for imglib2 will be: net.imglib2.algorithm.stats)
	minmax=ComputeMinMax(scaledimg)
	minmax.process()
	(min,max)=(minmax.getMin().get(),minmax.getMax().get())
	# Make a copy of the stack (converting to 8 bit as we go)
	stack = ImageStack(imp2.width, imp2.height)
	print "min = %e, max =%e" % (min,max)
	for i in xrange(1, imp2.getNSlices()+1):
		imp2.setSliceWithoutUpdate(i)
		ip=imp2.getProcessor()
		# set range
		ip.setMinAndMax(min,max)
		stack.addSlice(str(i), ip.convertToByte(True))
	
	# save copy of calibration info
	cal=imp.getCalibration()
	# close original image
	imp.close()
	# make an image plus with the copy
	scaled = ImagePlus(imp2.title, stack)
	
	# Deal with calibration info which didn't seem to come along for the ride
	cal.pixelWidth/=scalex
	cal.pixelHeight/=scaley
	cal.pixelDepth/=scalez
	scaled.setCalibration(cal)
	print "dx = %f; dy=%f; dz=%f" % (cal.pixelWidth,cal.pixelHeight,cal.pixelDepth)
	
	intif=infile+".tif"
	outtif=infile+"-filtered.tif"
	if anisofilter.upper() != 'FALSE':
		print("saving input file as "+intif)
		f=FileSaver(scaled)
		f.saveAsTiffStack(intif)
		scaled.close()
		# anisotropic filtering
		anisopts="-scanrange:10 -tau:2 -nsteps:2 -lambda:0.1 -ipflag:0 -anicoeff1:1 -anicoeff2:0 -anicoeff3:0"
		anisopts=anisopts+" -dx:%f -dy:%f -dz:%f" % (cal.pixelWidth,cal.pixelHeight,cal.pixelDepth)

		if sys.version_info > (2, 4):
			#for testing
			# subprocess.check_call(["cp",intif,outtif])
			subprocess.check_call([anisofilter]+anisopts.split(' ')+[intif,outtif])
		else:
			os.system(" ".join([anisofilter]+anisopts.split(' ')+[intif,outtif]))
		# Open anisofilter output back into Fiji
		print("Opening output tif: "+outtif)
		scaled = Opener().openImage(outtif)
		scaled.setCalibration(cal)
	
	# Hessian (tubeness)
	print("Running tubeness")
	if(runtube):
		tp=TubenessProcessor(1.0,False)
		result = tp.generateImage(scaled)
		IJ.run(result, "8-bit","")
	else:
		result=scaled
	# Save out file
	fileName, fileExtension = os.path.splitext(outfile)
	print("Saving as "+fileExtension+": "+outfile)
	if fileExtension.lower()=='.nrrd':
		nw=Nrrd_Writer()
		nw.setNrrdEncoding("gzip")
		nw.save(result,outfile)
	else:
		# Save to PIC
		IJ.run(result,"Biorad ...", "biorad=["+outfile+"]")
	scaled.close()
	result.close()
Ejemplo n.º 27
0
    for i in range(0, channels):
	imageProcessor = ShortProcessor(width, height)
	imageStack = ImageStack(width, height)
        for sphere in spheres:
            fnorm = int(round((sphere['f'][i] - fmin[i]) / (fmax[i] - fmin[i]) * 65536.0))
            x = sphere['cx']
            y = sphere['cy']
            d = sphere['r'] * 2
            imageProcessor.putPixel(x, y, fnorm)
	imageStack.addSlice(imageProcessor)
	channelImages.append(ImagePlus("Rendering C" + "%i" % (i + 1), imageStack))
	
    imageO = RGBStackMerge.mergeChannels(channelImages, False)
else:
    for i in range(0, channels):
	objectImage = ObjectCreator3D(sx, sy, sz)
	for sphere in spheres:
            fnorm = int(round((sphere['f'][i] - fmin[i]) / (fmax[i] - fmin[i]) * 65536.0))
            objectImage.createEllipsoid(
                sphere['cx'], sphere['cy'],	sphere['cz'],
		sphere['r'], sphere['r'], round(sphere['r'] / zscale),
		fnorm, False)
        channelImages.append(ImagePlus("Rendering C" + "%i" % (i + 1), objectImage.getStack()))
        
    imageO = RGBStackMerge.mergeChannels(channelImages, False)

# Save result
saver = FileSaver(imageO)
saver.saveAsTiffStack(outputFile)	
print "Saved " + outputFile
  #filelist = os.listdir(filedir)
  for root, directories, filenames in os.walk(filedir):
    print directories
    for filename in filenames:	
      if filename.lower().endswith('.lif'):
        print filedir
        print "..." + filename
        filebase = splitext(filename)[0]
        imps = getImps(os.path.join(filedir, filename))
        printInfo(imps)	
        for (counter, item) in enumerate(imps):
          #outimp = zproj(item)
          outimp = makeComposite(item)
          #outimp.show()
          #outname = filedir + filebase + "/" + "s" + str(counter) + ".tif"
          subname = ijtool.split(item.getTitle(), " - ")[1]
          #outname = filedir + filebase + "/" + subname + "_ZP.tif"
          outdir = os.path.join(filedir, "processed")
          outname = os.path.join(outdir, filebase + "_" + subname + "_" + str(counter) + "_Composite")
          print outname
          if not os.path.isdir(outdir):
            os.mkdir(outdir)
          fs = FileSaver(outimp)
          fs.saveAsTiffStack(outname+".tif")
          fs.saveAsJpeg(outname+".jpg")
          

#outimp = zproject(filepath)
#outimp.show()

Ejemplo n.º 29
0
def run():
    print "===== bBatchConvertTo8Bitv3 ====="

    # Expecting one argument: the file path
    if len(sys.argv) < 2:
        print "   We need at least one folder as input"
        print "	  Usage: ./fiji-macosx bBatchConvertTo8Bitv3 <folder-path>/"

        # Prompt user for a folder
        sourceFolder = DirectoryChooser(
            "Please Choose A Directory Of .tif Files").getDirectory()
        if not sourceFolder:
            return
    else:
        sourceFolder = sys.argv[1]  #assuming it ends in '/'

    #get user options
    okGo = getOptions()  # creates {numberOfChannels, replaceExisting}
    if okGo == -1:
        return 0

    destFolder = sourceFolder + "channels8/"

    #make destination directory
    if not os.path.isdir(destFolder):
        os.makedirs(destFolder)

    print "   Processing source folder: ", sourceFolder
    print "   Saving to destination folder: ", destFolder

    numOpened = 0
    numSaved = 0

    for filename in os.listdir(sourceFolder):
        startWithDot = filename.startswith(".")
        isMax = filename.endswith("max.tif")
        isTif = filename.endswith(".tif")

        if (not startWithDot) and (not isMax) and (isTif):
            shortName, fileExtension = os.path.splitext(filename)
            outPath = destFolder + "/" + filename
            outPath1 = destFolder + "/" + shortName + "_ch1" + ".tif"
            outPath2 = destFolder + "/" + shortName + "_ch2" + ".tif"

            #before we open, check if eventual dest exists
            if not replaceExisting:
                if numberOfChannels == 2 and os.path.exists(
                        outPath1) and os.path.exists(outPath2):
                    print "   8-Bit Destination file exists, not saving the image.", filename
                    continue  #with next iteration
                if numberOfChannels == 1 and os.path.exists(outPath):
                    print "   8-Bit Destination file exists, not saving the image.", filename
                    continue  #with next iteration

            print "   ===================================="
            print "   -> Opening", sourceFolder + filename
            imp = IJ.openImage(sourceFolder + filename)
            if imp is None:
                print "	     Could not open image from file:", filename
                continue  #with next iteration

            imp.show()
            numOpened += 1

            #i can get properties as long list of {key=value}
            #how do i then set each property in new imp1/imp2? Do IJ.openImagehave ot loop?
            #print imp.getProperties()

            #in the future IJ.openImagehavewant to have option to scale down to 512X512
            #run("Scale...", "x=- y=- z=1.0 width=512 height=512 depth=196 interpolation=Bilinear average process create title=20131007_a144_008_ch1-1.tif");

            print "      Image is: " + str(imp.width) + " X " + str(
                imp.height) + " X " + str(imp.getNSlices())
            if imp.getBitDepth() == 16:
                print "      Converting to 8-bit..."
                IJ.run("8-bit")

                if numberOfChannels == 2:
                    print "      deinterleaving"
                    IJ.run("Deinterleave", "how=2")
                    #makes 2 window

                    #ch2
                    imp2 = IJ.getImage()
                    fs = FileSaver(imp2)
                    print "      Saving 8bit File to", outPath2
                    fs.saveAsTiffStack(outPath2)
                    numSaved += 1
                    imp2.changes = 0
                    imp2.close()

                    #ch1
                    imp1 = IJ.getImage()
                    fs = FileSaver(imp1)
                    print "      Saving 8bit File to", outPath2
                    fs.saveAsTiffStack(outPath1)
                    numSaved += 1
                    imp1.changes = 0
                    imp1.close()
                elif numberOfChannels == 1:  #single channel
                    fs = FileSaver(imp)
                    print "      Saving 8bit File to", outPath
                    fs.saveAsTiffStack(outPath)
                    numSaved += 1
                    imp.changes = 0
                    imp.close()

            else:
                print "   File was not 16 bit???"

            imp.close()  #close original

        else:
            if isTif:
                #print "   ===================================="
                print "   -> Ignoring .tif:", filename

    print "   ==="
    print "   bBatchConvertTo8Bitv3.py is Done, Number Opened " + str(
        numOpened) + ", Number Saved ", str(numSaved)
    print "   ==="
Ejemplo n.º 30
0
def analyze(tempFile):
# Get currently selected image
#imp = WindowManager.getCurrentImage()
	imp = IJ.openImage(tempFile)
	imp.show()
	dims = imp.getDimensions();
	imp.setDimensions(dims[2], dims[4], dims[3]);
	#----------------------------
	# Create the model object now
	#----------------------------
	# Some of the parameters we configure below need to have
	# a reference to the model at creation. So we create an
	# empty model now.
	model = Model()
	# Send all messages to ImageJ log window.
	model.setLogger(Logger.IJ_LOGGER)
	#------------------------
	# Prepare settings object
	#------------------------
	settings = Settings()
	settings.setFrom(imp)
	print(settings.imageFileName)   
	# Configure detector - We use the Strings for the keys
	settings.detectorFactory = LogDetectorFactory()
	settings.detectorSettings = { 
    	'DO_SUBPIXEL_LOCALIZATION' : False,
    	'RADIUS' : 20.,
    	'TARGET_CHANNEL' : 1,
    	'THRESHOLD' : 0.95,
    	'DO_MEDIAN_FILTERING' : True,
	}  
	# Configure spot filters - Classical filter on quality
	#filter1 = FeatureFilter('QUALITY', 0.5, True)
	#settings.addSpotFilter(filter1)
	# Configure tracker - We want to allow merges and fusions
	settings.trackerFactory = SimpleSparseLAPTrackerFactory()
	settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap() #probably good enough
	#settings.trackerSettings['ALLOW_TRACK_SPLITTING'] = False
	#settings.trackerSettings['ALLOW_TRACK_MERGING'] = False
	settings.trackerSettings['LINKING_MAX_DISTANCE'] = 35.0
	settings.trackerSettings['GAP_CLOSING_MAX_DISTANCE']= 60.0
	settings.trackerSettings['MAX_FRAME_GAP']= 2
	# Configure track analyzers - Later on we want to filter out tracks 
	# based on their displacement, so we need to state that we want 
	# track displacement to be calculated. By default, out of the GUI, 
	# not features are calculated.   
	# The displacement feature is provided by the TrackDurationAnalyzer.
	settings.addTrackAnalyzer(TrackDurationAnalyzer())
	#-------------------
	# Instantiate plugin
	#-------------------
	trackmate = TrackMate(model, settings)
	ok = trackmate.process()
	if not ok:
		sys.exit(str(trackmate.getErrorMessage()))
	#----------------
	# Display results
	#----------------
	selectionModel = SelectionModel(model)
	displayer =  HyperStackDisplayer(model, selectionModel, imp)
	displayer.render()
	displayer.refresh()
	# Echo results with the logger we set at start:
	model.getLogger().log(str(model))
	print(str(settings))
	filename = os.path.splitext(settings.imageFileName)
	pathname = settings.imageFolder + "" + filename[0] + "tracks.xml"
	guicontroller = TrackMateGUIController(trackmate)
	newFile = File(pathname)
	ExportTracksToXML(guicontroller).export(model, settings, newFile)
	actionObject = CaptureOverlayAction()
	actionObject.execute(trackmate)
	imp = WindowManager.getCurrentImage()
	fileSaver = FileSaver(imp)
	fileSaver.saveAsTiffStack(settings.imageFolder + "" + filename[0] + "overlay.tif")
	WindowManager.closeAllWindows()
	guicontroller.quit()
	selectionModel.clearSelection();
	model.clearTracks(1)
Ejemplo n.º 31
0
def runOneTif(tifPath, dstTifPath):
	bPrintLog('=== runOneTif processing tif:' + tifPath, 3)

	bPrintLog('Loading file...', 3)
	imp = IJ.openImage(tifPath)  

	if imp is None:  
		bPrintLog('ERROR: could not open image from file:' + tifPath, 3)
		return 0  

	logStr = 'done loading file: ' + str(imp.width) + ' ' + str(imp.height) + ' ' + str(imp.getNSlices())
	bPrintLog(logStr, 3)

	numSlices = imp.getNSlices()
	if numSlices>1:
		pass
	else:
		bPrintLog('ERROR: number of slices must be more than one, file: ' + tifPath)
		return 0
	bPrintLog('numSlices: ' + str(numSlices), 3)
	
	infoStr = imp.getProperty("Info") #get all tags
	#print infoStr
	if infoStr is None:
		infoStr = ''
	infoStr += 'bAverageFrames=v0.1\n'
	imp.setProperty("Info", infoStr)

	imp.show()
	impWin = imp.getTitle()

	#
	# start body
	
	#infer type of file from
	# get the actual bit depth used (e.g. ScanImage is 11 bit, Prairie is 13 bit)
	header = bParseHeader(imp)
	b_sequence = ''
	if 'b_sequence' in header:
		b_sequence = str(header['b_sequence'])

	bPrintLog('b_sequence: ' + b_sequence, 3)
	
	madeAverage = 0

	
	# if numSlices is not divisable by gNumToAverage then chop a few slices off bottom/end
	if b_sequence.startswith('TSeries'):
		if globalOptions['gNumToAverage'] > 1:
			numToRemove = numSlices % globalOptions['gNumToAverage']
			if numToRemove > 0:
				bPrintLog('Removing bottom slices: ' + str(numToRemove), 3)
				# run("Slice Remover", "first=3 last=5 increment=1");
				removeArgs = 'first=' + str(numSlices-numToRemove+1) + ' last=' + str(numSlices) + ' increment=1'
				IJ.run('Slice Remover', removeArgs)
				numSlices = imp.getNSlices()
				bPrintLog('numSlices: ' + str(numSlices), 3)
				
			#fix this: if stack is really short this will not be taken
			if (numSlices > globalOptions['gNumToAverage']):
				bPrintLog('Taking average of ' + str(globalOptions['gNumToAverage']) + ' slices from ' + str(numSlices), 3)
				stackRegParams = 'projection=[Average Intensity] group=' + str(globalOptions['gNumToAverage'])
				IJ.run('Grouped Z Project...', stackRegParams) # makes window AVG_
		
				madeAverage = 1
				
				avgWindow = 'AVG_' + impWin
				avgImp = WindowManager.getImage(avgWindow)
				avgSlices = avgImp.getNSlices()
	
				# Grouped Z PRoject swaps slices for frames?
				tmpSlices = avgImp.getNSlices()
				tmpFrames = avgImp.getNFrames()
				if tmpFrames > 1:
					newSlices = tmpFrames
					newFrames = tmpSlices
					nChannels = 1
					bPrintLog('Swaping frames for slices after grouped z',3)
					bPrintLog('newSlices=' + str(newSlices) + ' newFrames='+str(newFrames), 4)
					avgImp.setDimensions(nChannels, newSlices, newFrames)
				
				infoStr += 'gNumToAverage=' + str(globalOptions['gNumToAverage']) + '\n'
				# I want to adjust the framePeriod, prairie would be 'b_framePeriod'
				avgImp.setProperty("Info", infoStr)
		else:
			avgImp = imp
			avgSlices = numSlices
		
	else:
		bPrintLog('Not taking average of sequence: ' + b_sequence,3)
		avgImp = imp
		avgSlices = numSlices

		
	if globalOptions['medianFilter']>0:
		bPrintLog('Running median filter: ' + str(globalOptions['medianFilter']), 3)
		medianArgs = 'radius=' + str(globalOptions['medianFilter']) + ' stack'
		IJ.run(avgImp, "Median...", medianArgs);
		infoStr += 'bMedianFilter=' + str(globalOptions['medianFilter']) + '\n'
		avgImp.setProperty("Info", infoStr)

	# convert to 8 bit
	# 1) read bit depth from header (e.g. 2^13)
	# 2) do math on image and convert to 8-bit
	# run("Divide...", "value=32 stack");
	if globalOptions['gConvertToEightBit']:
		bPrintLog('converting to 8-bit by dividing image down and then convert to 8-bit with ImageConverter.setDoScaling(False)', 3)
		bitDepth = 2^13
		divideBy = bitDepth / 2^8
		# divide the 13 bit image down to 8 bit
		#run("Divide...", "value=32 stack");
		bPrintLog('divideBy:' + str(divideBy), 3)
		divideArgs = 'value=' + str(divideBy) + ' stack'
		IJ.run(avgImp, "Divide...", divideArgs);
		# convert to 8-bit will automatically scale, to turn this off use
		# eval("script", "ImageConverter.setDoScaling(false)"); 
		ImageConverter.setDoScaling(False)
		# run("8-bit");
		bPrintLog('converting to 8-bit with setDoScaling False', 3)
		IJ.run(avgImp, "8-bit", '');
	
	bPrintLog('Saving stack with ' + str(avgSlices) + ' slices:' + dstTifPath, 3)
	fs = FileSaver(avgImp)
	if avgSlices>1:
		fs.saveAsTiffStack(dstTifPath)
	else:
		fs.saveAsTiff(dstTifPath)

	if madeAverage:
		avgImp.changes = 0
		avgImp.close()
	
	imp.changes = 0
	imp.close()
	
	# end body
	#
	
	# why was this here
	#imp.changes = 0
	#imp.close()

	return 1
Ejemplo n.º 32
0
		thr1, thrimp1 = calculateThreshold(imp1, roi, methods[0])
		thr2, thrimp2 = calculateThreshold(imp2, roi, methods[1])
		
		cursor = TwinCursor(img1.randomAccess(), img2.randomAccess(), Views.iterable(mask).localizingCursor())
		rtype = img1.randomAccess().get().createVariable()
		raw = manders.calculateMandersCorrelation(cursor, rtype)
		rthr1 = rtype.copy()
		rthr2 = rtype.copy()
		rthr1.set(thr1)
		rthr2.set(thr2)
		cursor.reset()
		thrd = manders.calculateMandersCorrelation(cursor, rthr1, rthr2, ThresholdMode.Above)
		print "Results are: %f %f %f %f" % (raw.m1, raw.m2, thrd.m1, thrd.m2)

		results.incrementCounter()
		rowno = results.getCounter() - 1
		results.setValue("Cell", rowno, int(rowno))
		results.setValue("Threshold 1", rowno, int(thr1))
		results.setValue("Threshold 2", rowno, int(thr2))
		results.setValue("M1 raw", rowno, float(raw.m1))
		results.setValue("M2 raw", rowno, float(raw.m2))
		results.setValue("M1 thrd", rowno, float(thrd.m1))
		results.setValue("M2 thrd", rowno, float(thrd.m2))
		
		thrimp = RGBStackMerge.mergeChannels([thrimp1, thrimp2], False)
		saver = FileSaver(thrimp)
		saver.saveAsTiffStack(outputDir + "Cell_%i-" % results.getCounter() + title + ".tif")
		thrimp.close()

results.show("Colocalization results")
wcount = wm.getWindowCount()
if wcount == 0:
    log.warn("No windows open, nothing to do.")
    sys.exit()

log.info("Number of open windows: %s" % wcount)
log.info("Selected [%s] as destination folder." % target)

# determine padding width for filenames
pad = len(str(wcount))

for wid in range(1, wcount + 1):
    imp = wm.getImage(wid)
    imgid = wm.getNthImageID(wid)
    log.debug("window id: %s, imageID: %s" % (wid, wm.getNthImageID(wid)))

    # Construct filename
    filename = 'img_' + str(wid).zfill(pad) + '.tif'
    filepath = target + '/' + filename
    fs = FileSaver(imp)
    if imp.getImageStackSize() > 1:
        if not fs.saveAsTiffStack(filepath):
            log.error("Error saving current image, stopping.")
            sys.exit()
    else:
        if not fs.saveAsTiff(filepath):
            log.error("Error saving current image, stopping.")
            sys.exit()

log.info("Successfully saved %s files." % wcount)
def run():
	print "===== Batch Convert Scan Image 4 ====="

	# Expecting one argument: the file path
	if len(sys.argv) < 2:
		print "   We need a hard-drive folder with .tif stacks as input"
		print "	  Usage: ./fiji-macosx bBatchConvertTo8Bitv3 <folder-path>/"

		# Prompt user for a folder
		sourceFolder = DirectoryChooser("Please Choose A Directory Of .tif Files").getDirectory()
		if not sourceFolder:
			return
	else:
		sourceFolder = sys.argv[1] #assuming it ends in '/'

	destFolder = sourceFolder + "scanimage4/"
	destMaxFolder = destFolder + "max/"

	#make destination directory
	if not os.path.isdir(destFolder):
		os.makedirs(destFolder)

	#make max destination directory
	if not os.path.isdir(destMaxFolder):
		os.makedirs(destMaxFolder)
	
	print "   Processing source folder: ", sourceFolder  
	print "   Saving to destination folder: ", destFolder  
	IJ.log("   ====== Starting Batch Convert Scan Image 4 ======")
	IJ.log("   Processing source folder: " + sourceFolder)
	IJ.log("   Saving to destination folder: " + destFolder)

	numOpened = 0
	numSaved = 0

	for filename in os.listdir(sourceFolder):	
		startWithDot = filename.startswith(".")
		isMax = filename.endswith("max.tif")
		isTif = filename.endswith(".tif")

		if (not startWithDot) and (not isMax) and (isTif):
			shortName, fileExtension = os.path.splitext(filename)
			
			#source .tif output (after conversion)
			outPath = destFolder + filename

			#max projection output
			outMaxPath = destMaxFolder + "max_" + filename
			
			#before we open, check if eventual dest exists
			if os.path.exists(outPath):
				msgStr = "   Destination file exists, not processing the image:" + filename
				print msgStr
				IJ.log(msgStr)
				continue #with next iteration
			
			print "   ===================================="
			msgStr = "   -> Opening " + sourceFolder+filename  
			print msgStr
			IJ.log(msgStr)
			imp = IJ.openImage(sourceFolder + filename)
			if imp is None:  
				msgStr = "	     ERROR: Could not open image from file: " + filename  
				print msgStr
				IJ.log(msgStr)
				continue   #with next iteration
			
			imp.show()
			numOpened +=1

			msgStr = "      Original Image is: " + str(imp.width) + " X " + str(imp.height) + " X " + str(imp.getNSlices())
			print msgStr
			IJ.log(msgStr)
			if 1:
				msgStr = "      Removing Calibration From ScanImage 4 .tif"
				print msgStr
				IJ.log(msgStr)

				#20140810, I CAN'T BELIEVE I FINALLY FOUND THIS !!!
				infoStr = imp.getProperty("Info")
				#print infoStr

				#scanimage4 has a linear Calibration Function: y = a+bx
				#  a: -32768.000000
				#  b: 1.000000
				#  Unit: "Gray Value"
				#for some reason scanimage4 is setting a linear image calibration, we see negative values but there are NOT there
				cal = imp.getCalibration()
				calCoeff = cal.getCoefficients()
				msgStr = '        calibration is y=ax+b' + ' a=' + str(calCoeff[0]) + ' b=' + str(calCoeff[1])
				print msgStr
				IJ.log(msgStr)

				#append calibration to info string
				imp.setCalibration(None)
				infoStr += 'calibCoeff_a = ' + str(calCoeff[0]) + '\n'
				infoStr += 'calibCoeff_b = ' + str(calCoeff[1]) + '\n'

				#i have appended to Info, update it
				#found this burried here: http://code.google.com/p/fiji-bi/source/browse/ij/ImagePlus.java?repo=imageja&name=imagej
				imp.setProperty("Info", infoStr);

				#get and print out min/max
				theMin = StackStatistics(imp).min
				theMax = StackStatistics(imp).max
				msgStr = '        min=' + str(theMin) + ' max=' + str(theMax)
				print msgStr
				IJ.log(msgStr)

				#subtract the linear calibration slope 'a' (what about intercept 'b' ?)
				#coefficient 'a' is normally negative, this is what we are using 'Add'
				#run("Subtract...", "value=32768 stack");
				subArgVal = 'value=%s stack' % (calCoeff[0],)
				IJ.run('Add...', subArgVal)
				
				#save file
				fs = FileSaver(imp)
				msgStr = "      Saving File to" + outPath
				print msgStr
				IJ.log(msgStr)
					
				numSlices = imp.getNSlices() 

				if (numSlices>1):
					fs.saveAsTiffStack(outPath)
				else:
					fs.saveAsTiff(outPath)
				numSaved += 1

				#max
				if (numSlices>1):
					maxCmdParams = 'start=1' + ' stop=' + str(numSlices) + ' projection=[Max Intensity]'
					IJ.run("Z Project...", maxCmdParams)
				
				impMax = IJ.getImage()
				fs = FileSaver(impMax)
				print "      Saving Max File to", outMaxPath
				fs.saveAsTiff(outMaxPath)
				
				#close max
				impMax.changes = 0
				impMax.close()
				
				#close original
				imp.changes = 0
				imp.close()

			else:
				print "   File was not 16 bit???"
			
			imp.close() #close original

		else:  
			if (not startWithDot) and isTif:
				#print "   ===================================="
				print filename
				msgStr = "   -> Ignoring .tif:" + filename
				print msgStr
				IJ.log(msgStr)

	msgStr = "   Batch Convert Scan Image 4 is Done, Number Opened " + str(numOpened) + ", Number Saved " + str(numSaved)
	print "   ==="
	print msgStr
	print "   ==="
	IJ.log(msgStr)
Ejemplo n.º 35
0
def runOneTif(tifPath, dstTifPath):
    bPrintLog('=== runOneTif processing tif:' + tifPath, 3)

    bPrintLog('Loading file...', 3)
    imp = IJ.openImage(tifPath)

    if imp is None:
        bPrintLog('ERROR: could not open image from file:' + tifPath, 3)
        return 0

    logStr = 'done loading file: ' + str(imp.width) + ' ' + str(
        imp.height) + ' ' + str(imp.getNSlices())
    bPrintLog(logStr, 3)

    numSlices = imp.getNSlices()
    bPrintLog('numSlices: ' + str(numSlices), 3)

    infoStr = imp.getProperty("Info")  #get all tags
    if infoStr is None:
        infoStr = ''
    infoStr += 'bMaxProject=v0.1\n'
    imp.setProperty("Info", infoStr)

    imp.show()
    impWin = imp.getTitle()

    # BODY

    # get the bit depth form opened imp
    impBitDepth = imp.getBitDepth()
    bPrintLog('image bit depth:' + str(impBitDepth), 3)

    # get the actual bit depth used (e.g. ScanImage is 11 bit, Prairie is 13 bit)
    header = bParseHeader(imp)
    actualBitDepth = impBitDepth
    if 'b_bitDepth' in header:
        actualBitDepth = int(header['b_bitDepth'])
    bPrintLog('actual bit depth:' + str(actualBitDepth), 3)

    made8bit = 0
    if impBitDepth == 8:
        made8bit = 1
    else:
        made8bit = 1
        if 0:
            divideBy = math.pow(2, actualBitDepth) / math.pow(
                2, 8)  # divide the 13 bit or 11 bit image down to 8 bit
            bPrintLog('diving by:' + str(divideBy), 3)
            bPrintLog(
                'converting to 8-bit by dividing image by ' + str(divideBy) +
                ' and then convert to 8-bit with ImageConverter.setDoScaling(False)',
                3)
            #run("Divide...", "value=32 stack");
            divideArgs = 'value=' + str(divideBy) + ' stack'
            IJ.run(imp, "Divide...", divideArgs)
        # convert to 8-bit will automatically scale, to turn this off use
        # eval("script", "ImageConverter.setDoScaling(false)");
        # 20170810 was this
        #ImageConverter.setDoScaling(False)
        ImageConverter.setDoScaling(True)
        # run("8-bit");
        bPrintLog('converting to 8-bit with setDoScaling False', 3)
        IJ.run(imp, "8-bit", '')
        #does this in place, no new window

    # save
    bPrintLog('Saving stack with ' + str(numSlices) + ' slices:' + dstTifPath,
              3)
    fs = FileSaver(imp)
    if numSlices > 1:
        fs.saveAsTiffStack(dstTifPath)
    else:
        fs.saveAsTiff(dstTifPath)

    # END BODY

    # close original
    imp.changes = 0
    imp.close()
def run():
	print "===== bBatchConvertTo8Bitv3 ====="

	global numberOfChannels
	global replaceExisting

	# Expecting one argument: the file path
	if len(sys.argv) < 2:
		print "   We need a hard-drive folder with .tif stacks as input"
		print "	  Usage: ./fiji-macosx bBatchConvertTo8Bitv3 <folder-path>/"

		# Prompt user for a folder
		sourceFolder = DirectoryChooser("Please Choose A Directory Of .tif Files").getDirectory()
		if not sourceFolder:
			return
	else:
		sourceFolder = sys.argv[1] #assuming it ends in '/'

	#get user options
	okGo = getOptions() # creates {numberOfChannels, replaceExisting}
	if okGo == -1:
		return 0

	destFolder = sourceFolder + "channels8/"
	destMaxFolder = sourceFolder + "max/"

	#make destination directory
	if not os.path.isdir(destFolder):
		os.makedirs(destFolder)

	#make max destination directory
	if not os.path.isdir(destMaxFolder):
		os.makedirs(destMaxFolder)
	
	print "   Processing source folder: ", sourceFolder  
	print "   Saving to destination folder: ", destFolder  
	IJ.log("   ====== Startin bBatchConvertTo8Bitv3 ======")
	IJ.log("   Processing source folder: " + sourceFolder)
	IJ.log("   Saving to destination folder: " + destFolder)

	numOpened = 0
	numSaved = 0

	for filename in os.listdir(sourceFolder):	
		startWithDot = filename.startswith(".")
		isMax = filename.endswith("max.tif")
		isTif = filename.endswith(".tif")

		if (not startWithDot) and (not isMax) and (isTif):
			shortName, fileExtension = os.path.splitext(filename)
			outPath = destFolder + "/" + filename
			outPath1 = destFolder + "/" + shortName + "_ch1" + ".tif"
			outPath2 = destFolder + "/" + shortName + "_ch2" + ".tif"

			#max projection output
			outMaxPath = destMaxFolder + "/" + "max_" + filename
			outMaxPath1 = destMaxFolder + "/" + "max_" + shortName + "_ch1" + ".tif"
			outMaxPath2 = destMaxFolder + "/" + "max_" + shortName + "_ch2" + ".tif"
			
			#before we open, check if eventual dest exists
			if not replaceExisting:
				if numberOfChannels == 2 and os.path.exists(outPath1) and os.path.exists(outPath2):
					msgStr = "   8-Bit Destination file exists, not processing the image:" + filename
					print msgStr
					IJ.log(msgStr)
					continue #with next iteration
				if numberOfChannels == 1 and os.path.exists(outPath):
					msgStr = "   8-Bit Destination file exists, not processing the image:" + filename
					print msgStr
					IJ.log(msgStr)
					continue #with next iteration
			
			print "   ===================================="
			msgStr = "   -> Opening " + sourceFolder+filename  
			print msgStr
			IJ.log(msgStr)
			imp = IJ.openImage(sourceFolder + filename)
			if imp is None:  
				msgStr = "	     ERROR: Could not open image from file: " + filename  
				print msgStr
				IJ.log(msgStr)
				continue   #with next iteration
			
			imp.show()
			numOpened +=1
			
			#i can't get properties as long list of {key=value}
			#how do i then set each property in new imp1/imp2? Do IJ.openImagehave ot loop?
			#infoProperty = imp.getInfoProperty() #Returns the "Info" property string, java.lang.String
			#print 'infoProperty'
			#print infoProperty

			#.getProp(key) #Returns the value from the "Info" property string associated with 'key'
			
			#myProp = imp.getProperties() #returns java.util.Properties
			#print 'myProp (really long)'
			#print myProp

			#print 'patrick'
			#myList = str(myProp).split('\r')
			
			#I want' to strip out 'Info=ImageDescription: '
			#myList = re.sub('Info=ImageDescription: ', '', str(myList))
			
			#for i in range (0,len(myList)):
			#	myList[i] = myList[i].split('=')
			
			#print myList[0]
			#print myList[1]
			#print myList[2]
			#print myList[3]

			#imp.setProperty('myStr', 1)

			#try usinf ImageStack
			#myImageStack = imp.getImageStack()
			
			#eventuallly just call imp.getProp(str) which Returns the value from the "Info"
			
			#in the future IJ.openImagehavewant to have option to scale down to 512X512
			#run("Scale...", "x=- y=- z=1.0 width=512 height=512 depth=196 interpolation=Bilinear average process create title=20131007_a144_008_ch1-1.tif");

			msgStr = "      Original Image is: " + str(imp.width) + " X " + str(imp.height) + " X " + str(imp.getNSlices())
			print msgStr
			IJ.log(msgStr)
			if imp.getBitDepth() == 16:
				msgStr = "      Converting to 8-bit..."
				print msgStr
				IJ.log(msgStr)
				IJ.run("8-bit")

				if numberOfChannels == 2:
					msgStr = "      deinterleaving"
					print msgStr
					IJ.run("Deinterleave", "how=2"); #makes 2 window
					
					#
					#ch2
					imp2 = IJ.getImage()
					fs = FileSaver(imp2)
					msgStr = "      ch2: Saving deinterleaved 8bit File to: " + outPath2
					print msgStr
					IJ.log(msgStr)

					numSlices = imp2.getNSlices() 
					if (numSlices>1):
						fs.saveAsTiffStack(outPath2)
					else:
						fs.saveAsTiff(outPath2)
						
					#max, ch2
					if (numSlices>1):
						maxCmdParams = 'start=1' + ' stop=' + str(numSlices) + ' projection=[Max Intensity]'
						IJ.run("Z Project...", maxCmdParams)
						#impMax2 = IJ.getImage()
						
					print "      Saving 8bit Max File to", outMaxPath2
					impMax2 = IJ.getImage()
					fs = FileSaver(impMax2)
					fs.saveAsTiff(outMaxPath2)
					
					impMax2.changes = 0
					impMax2.close()
					
					numSaved += 1
					imp2.changes = 0
					imp2.close()
					
					#
					#ch1
					imp1 = IJ.getImage()
					fs = FileSaver(imp1)
					msgStr = "      ch1: Saving deinterleaved 8bit File to" + outPath1
					print msgStr
					
					numSlices = imp1.getNSlices() 
					if (numSlices>1):
						fs.saveAsTiffStack(outPath1)
					else:
						fs.saveAsTiff(outPath1)

					#max, ch1
					if (numSlices>1):
						maxCmdParams = 'start=1' + ' stop=' + str(numSlices) + ' projection=[Max Intensity]'
						IJ.run("Z Project...", maxCmdParams)
					
					impMax1 = IJ.getImage()
					fs = FileSaver(impMax1)
					msgStr = "      Saving 8bit Max File to" + outMaxPath1
					print msgStr
					IJ.log(msgStr)
					fs.saveAsTiff(outMaxPath1)
					impMax1.changes = 0
					impMax1.close()

					numSaved += 1
					imp1.changes = 0
					imp1.close()
				
				elif numberOfChannels == 1: #single channel
					fs = FileSaver(imp)
					msgStr = "      Saving 8bit File to" + outPath
					print msgStr
					IJ.log(msgStr)
					
					numSlices = imp.getNSlices() 

					if (numSlices>1):
						fs.saveAsTiffStack(outPath)
					else:
						fs.saveAsTiff(outPath)
					numSaved += 1

					#max
					if (numSlices>1):
						maxCmdParams = 'start=1' + ' stop=' + str(numSlices) + ' projection=[Max Intensity]'
						IJ.run("Z Project...", maxCmdParams)
					
					impMax = IJ.getImage()
					fs = FileSaver(impMax)
					print "      Saving 8bit Max File to", outMaxPath
					fs.saveAsTiff(outMaxPath)
					impMax.changes = 0
					impMax.close()

					imp.changes = 0
					imp.close()

			else:
				print "   File was not 16 bit???"
			
			imp.close() #close original

		else:  
			if (not startWithDot) and isTif:
				#print "   ===================================="
				print filename
				msgStr = "   -> Ignoring .tif:" + filename
				print msgStr
				IJ.log(msgStr)

	msgStr = "   bBatchConvertTo8Bitv3.py is Done, Number Opened " + str(numOpened) + ", Number Saved " + str(numSaved)
	print "   ==="
	print msgStr
	print "   ==="
	IJ.log(msgStr)
def PrepareDatabase(minw, maxw, baseDir, aspectRatio, majorWidth, majorHeight):
	outputpath = baseDir + "/" + str(majorWidth) + "_" + str(majorHeight) + "_orig.tif"
	#initialize stacks and labels
	stackScaled = []
	stackOrig = ImageStack(majorWidth, majorHeight)
	imageNames = []
	for i in range(minw, maxw+1):
		stackScaled.append(ImageStack(i, int(round(i/aspectRatio, 0))))
		imageNames.append('')

	counter = 0

	# initialize zip file for originals
	zf = zipfile.ZipFile(baseDir + "/originals.zip", mode='w', compression=zipfile.ZIP_DEFLATED, allowZip64=1)
	zf.writestr('from_string.txt', 'hello')
	zf.close()
	zf = zipfile.ZipFile(baseDir + "/originals.zip", mode='a', compression=zipfile.ZIP_DEFLATED, allowZip64=1)

	for root, dirs, files in os.walk(str(baseDir)):
		for f1 in files:
			if f1.endswith(".jpg") or f1.endswith(".jpe") or f1.endswith(".jpeg"):
				id = root + "/" +  f1
				IJ.redirectErrorMessages()
				IJ.redirectErrorMessages(1)
				imp = IJ.openImage(id)
				if imp is None:
					print "Couldn\'t open image from file:", id
					continue
				# skip non RGBimages
				if imp.getProcessor().getNChannels() != 3:
					print "Skipping non RGB image:", id
					continue
				#skip images with different aspect ratio
				width = imp.getWidth()
				height = imp.getHeight()
				ratio = round(float(width)/float(height), 2) # this makes the ratio filering approximate, minor variations in image dimensions will be ignored
				if ratio != aspectRatio:
					IJ.log("Skipping image of size: " + str(width) + "," + str(height))
					continue
				# now scale the image within a given range
				scale = Scale(imp.getProcessor())
				IJ.log("Scaling image " + str(counter) + " " + str(id))
				for i in range(minw, maxw+1):
					stackScaled[i-minw].addSlice(None, ScaleImageToSize(scale, i, int(round(i/aspectRatio, 0))))
					imageNames[i-minw] += str(id) + ";"
				# save the originals to a temp directory
				scaledOrig = ImagePlus(None, ScaleImageToSize(scale, majorWidth, majorHeight))
				SaveToZip(zf, scaledOrig, baseDir, counter)
				counter += 1
	zf.close()
	# save the stacks
	for i in range(minw, maxw+1):
		impScaled = ImagePlus(str(minw) + "_" + str(int(round(i/aspectRatio, 0))), stackScaled[i-minw])
		impScaled.show()
		#print imageNames
		impScaled.setProperty('Info', imageNames[i-minw][:-1])
		fs = FileSaver(impScaled)
		filepath = baseDir + "/" + str(i) + "_" + str(int(round(i/aspectRatio, 0))) + ".tif"
		IJ.log("Saving output stack" + str(filepath))
		fs.saveAsTiffStack(filepath)
		#IJ.save(impScaled, filepath);
		IJ.log("Done")
Ejemplo n.º 38
0
def run():
    print "===== Batch Convert Scan Image 4 ====="

    # Expecting one argument: the file path
    if len(sys.argv) < 2:
        print "   We need a hard-drive folder with .tif stacks as input"
        print "	  Usage: ./fiji-macosx bBatchConvertTo8Bitv3 <folder-path>/"

        # Prompt user for a folder
        sourceFolder = DirectoryChooser(
            "Please Choose A Directory Of .tif Files").getDirectory()
        if not sourceFolder:
            return
    else:
        sourceFolder = sys.argv[1]  #assuming it ends in '/'

    destFolder = sourceFolder + "scanimage4/"
    destMaxFolder = destFolder + "max/"

    #make destination directory
    if not os.path.isdir(destFolder):
        os.makedirs(destFolder)

    #make max destination directory
    if not os.path.isdir(destMaxFolder):
        os.makedirs(destMaxFolder)

    print "   Processing source folder: ", sourceFolder
    print "   Saving to destination folder: ", destFolder
    IJ.log("   ====== Starting Batch Convert Scan Image 4 ======")
    IJ.log("   Processing source folder: " + sourceFolder)
    IJ.log("   Saving to destination folder: " + destFolder)

    numOpened = 0
    numSaved = 0

    for filename in os.listdir(sourceFolder):
        startWithDot = filename.startswith(".")
        isMax = filename.endswith("max.tif")
        isTif = filename.endswith(".tif")

        if (not startWithDot) and (not isMax) and (isTif):
            shortName, fileExtension = os.path.splitext(filename)

            #source .tif output (after conversion)
            outPath = destFolder + filename

            #max projection output
            outMaxPath = destMaxFolder + "max_" + filename

            #before we open, check if eventual dest exists
            if os.path.exists(outPath):
                msgStr = "   Destination file exists, not processing the image:" + filename
                print msgStr
                IJ.log(msgStr)
                continue  #with next iteration

            print "   ===================================="
            msgStr = "   -> Opening " + sourceFolder + filename
            print msgStr
            IJ.log(msgStr)
            imp = IJ.openImage(sourceFolder + filename)
            if imp is None:
                msgStr = "	     ERROR: Could not open image from file: " + filename
                print msgStr
                IJ.log(msgStr)
                continue  #with next iteration

            imp.show()
            numOpened += 1

            msgStr = "      Original Image is: " + str(
                imp.width) + " X " + str(imp.height) + " X " + str(
                    imp.getNSlices())
            print msgStr
            IJ.log(msgStr)
            if 1:
                msgStr = "      Removing Calibration From ScanImage 4 .tif"
                print msgStr
                IJ.log(msgStr)

                #20140810, I CAN'T BELIEVE I FINALLY FOUND THIS !!!
                infoStr = imp.getProperty("Info")
                #print infoStr

                #scanimage4 has a linear Calibration Function: y = a+bx
                #  a: -32768.000000
                #  b: 1.000000
                #  Unit: "Gray Value"
                #for some reason scanimage4 is setting a linear image calibration, we see negative values but there are NOT there
                cal = imp.getCalibration()
                calCoeff = cal.getCoefficients()
                msgStr = '        calibration is y=ax+b' + ' a=' + str(
                    calCoeff[0]) + ' b=' + str(calCoeff[1])
                print msgStr
                IJ.log(msgStr)

                #append calibration to info string
                imp.setCalibration(None)
                infoStr += 'calibCoeff_a = ' + str(calCoeff[0]) + '\n'
                infoStr += 'calibCoeff_b = ' + str(calCoeff[1]) + '\n'

                #i have appended to Info, update it
                #found this burried here: http://code.google.com/p/fiji-bi/source/browse/ij/ImagePlus.java?repo=imageja&name=imagej
                imp.setProperty("Info", infoStr)

                #get and print out min/max
                theMin = StackStatistics(imp).min
                theMax = StackStatistics(imp).max
                msgStr = '        min=' + str(theMin) + ' max=' + str(theMax)
                print msgStr
                IJ.log(msgStr)

                #subtract the linear calibration slope 'a' (what about intercept 'b' ?)
                #coefficient 'a' is normally negative, this is what we are using 'Add'
                #run("Subtract...", "value=32768 stack");
                subArgVal = 'value=%s stack' % (calCoeff[0], )
                IJ.run('Add...', subArgVal)

                #save file
                fs = FileSaver(imp)
                msgStr = "      Saving File to" + outPath
                print msgStr
                IJ.log(msgStr)

                numSlices = imp.getNSlices()

                if (numSlices > 1):
                    fs.saveAsTiffStack(outPath)
                else:
                    fs.saveAsTiff(outPath)
                numSaved += 1

                #max
                if (numSlices > 1):
                    maxCmdParams = 'start=1' + ' stop=' + str(
                        numSlices) + ' projection=[Max Intensity]'
                    IJ.run("Z Project...", maxCmdParams)

                impMax = IJ.getImage()
                fs = FileSaver(impMax)
                print "      Saving Max File to", outMaxPath
                fs.saveAsTiff(outMaxPath)

                #close max
                impMax.changes = 0
                impMax.close()

                #close original
                imp.changes = 0
                imp.close()

            else:
                print "   File was not 16 bit???"

            imp.close()  #close original

        else:
            if (not startWithDot) and isTif:
                #print "   ===================================="
                print filename
                msgStr = "   -> Ignoring .tif:" + filename
                print msgStr
                IJ.log(msgStr)

    msgStr = "   Batch Convert Scan Image 4 is Done, Number Opened " + str(
        numOpened) + ", Number Saved " + str(numSaved)
    print "   ==="
    print msgStr
    print "   ==="
    IJ.log(msgStr)
Ejemplo n.º 39
0
	def run (self):
		# make output folder
		if not os.path.isdir(self.dstFolder):
			os.makedirs(self.dstFolder)

		tifFileName = os.path.split(self.tifFilePath)[1]
		isCh1 = self.tifFilePath.endswith('_ch1.tif')
		isCh2 = self.tifFilePath.endswith('_ch2.tif')

		doThisFilePath = ''
		if self.alignmentChannel==1 and isCh1:
			doThisFilePath = self.tifFilePath
		elif self.alignmentChannel==2 and isCh2:
			doThisFilePath = self.tifFilePath
		
		if (doThisFilePath):
			###
			###
			bPrintLog('Loading file: ' + doThisFilePath, 3)
			imp = IJ.openImage(doThisFilePath)  

			if imp is None:  
				print "ERROR: could not open image from file:", doThisFilePath
				return -1  

			d = imp.getDimensions() # Returns the dimensions of this image (width, height, nChannels, nSlices, nFrames) as a 5 element int array.
			logStr = 'dimensions are w:' + str(d[0]) + ' h:' + str(d[1]) + ' channels:' + str(d[2]) + ' slices:' + str(d[3]) + ' frames:' + str(d[4])
			bPrintLog(logStr, 3)
			
			'''
			this is not designed to handle stacks that have frames !!!
			'''
			##
			numSlices = imp.getNSlices()
			if numSlices>1:
				pass
			else:
				numFrames = imp.getNFrames()
				
				if numFrames > 1:
					# swap nFrames with nSLices
					numSlices = numFrames
					numFrames = 1
					nChannels = 1
					
					bPrintLog('Swapping frames for slices. numSlices=' + str(numSlices) + ' numFrames=' + str(numFrames), 3)
					imp.setDimensions(nChannels, numSlices, numFrames)
				else:
					bPrintLog('ERROR: number of slices must be more than one, file: ' + tifFileName)
					return -1
			##
			
			# get the stack header (e.g. infoStr)
			infoStr = imp.getProperty("Info") #get all tags
			if infoStr is None:
				infoStr = ''

			## median filter
			if self.medianFilter > 0:
				bPrintLog('Running median filter: ' + str(self.medianFilter), 3)
				medianArgs = 'radius=' + str(self.medianFilter) + ' stack'
				IJ.run(imp, "Median...", medianArgs);
				infoStr += 'bMedianFilter=' + str(self.medianFilter) + '\n'
				imp.setProperty("Info", infoStr)
			
			#add to stack header
			infoStr += 'b_AlignFolder=v0.0\n'
			imp.setProperty("Info", infoStr)
			
			imp.show()
			impWin = imp.getTitle()

			#show the slice we start alignment on
			middleSlice = int(math.floor(numSlices / 2))
			imp.setSlice(middleSlice)
			
			transformationFile = self.dstFolder + tifFileName + '.txt'
		
			if run_alignment:
				bPrintLog('Running MultiStackReg for: ' + tifFileName, 3)
				stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' %(impWin,transformationFile)
				IJ.run('MultiStackReg', stackRegParams)
			else:
				bPrintLog('DEBUG: NOT running MultiStackReg for: ' + tifFileName, 3)

			# save alignment
			bPrintLog('Saving aligned stack():' + self.dstFolder + tifFileName, 3)
			fs = FileSaver(imp)
			if numSlices>1:
				fs.saveAsTiffStack(self.dstFolder + tifFileName)
			else:
				fs.saveAsTiff(self.dstFolder + tifFileName)
			
			imp.changes = 0
			imp.close()

			###
			###
			#open and run alignment on other channel
			if isCh1:
				otherFilePath = self.tifFilePath.strip('_ch1.tif') + '_ch2.tif'
			elif isCh2:
				otherFilePath = self.tifFilePath.strip('_ch2.tif') + '_ch1.tif'

			if os.path.isfile(otherFilePath):
				otherFileName = os.path.split(otherFilePath)[1]
				
				bPrintLog('Loading [OTHER] file: ' + doThisFilePath, 3)
				imp = IJ.openImage(otherFilePath)  

				if imp is None:  
					print "ERROR: could not open other image from file:", otherFilePath
					return -1  

				##
				numSlices = imp.getNSlices()
				if numSlices>1:
					pass
				else:
					numFrames = imp.getNFrames()
					
					if numFrames > 1:
						# swap nFrames with nSLices
						numSlices = numFrames
						numFrames = 1
						nChannels = 1
						
						bPrintLog('Swapping frames for slices. numSlices=' + str(numSlices) + ' numFrames=' + str(numFrames), 3)
						imp.setDimensions(nChannels, numSlices, numFrames)
					else:
						bPrintLog('ERROR: number of slices must be more than one, file: ' + tifFileName)
						return -1
				##
				
				#add to stack header
				infoStr = imp.getProperty("Info") #get all tags
				if infoStr is None:
					infoStr = ''
				infoStr += 'b_AlignFolder=v0.0' + '\n'
				imp.setProperty("Info", infoStr)

				imp.show()
				impWin = imp.getTitle()

				if run_alignment:
					bPrintLog('Running MultiStackReg for: ' + otherFileName, 3)
					stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(impWin,transformationFile)
					IJ.run('MultiStackReg', stackRegParams)		
				else:
					bPrintLog('DEBUG: Not running MultiStackReg for: ' + otherFileName, 3)

				#save alignment
				bPrintLog('Saving aligned stack():' + self.dstFolder + otherFileName, 3)
				fs = FileSaver(imp)
				if numSlices>1:
					fs.saveAsTiffStack(self.dstFolder + otherFileName)
				else:
					fs.saveAsTiff(self.dstFolder + otherFileName)

				imp.changes = 0
				imp.close()
Ejemplo n.º 40
0
for i in range(wcount):
	### image ID lists start with 1, not 0
	## wid = id + 1
	imgid = wm.getNthImageID(i+1)
	# print "window id ", i+1, ":", wm.getNthImageID(i+1)
	imp = wm.getImage(i+1)
	fs = FileSaver(imp)
	# Print image details
	# print "  title:", imp.title
	# print "  current window:", wm.getCurrentWindow()
	# Construct filename
	filename = 'tile_' + str(i+1).zfill(pad) + '.tif'
	filepath = target + '/' + filename
	#print "filename:", filename
	if fs.saveAsTiffStack(filepath):
		print "imageID", imgid, "saved as", filename
	else:
		print "ERROR saving imageID", imgid, "file at", filepath

#print "ID list of windows:", WindowManager.getIDList()
##idlist = WindowManager.getIDList()
##for wid in idlist:
##	print "window id:", wid
##
##print "front window:", WindowManager.getFrontWindow()


# wm.putBehind()

#print "width:", imp.width