def autoProcAZtecImage(fwMicrons, wrkDir, barWid=0.1, barHt=9, barFnt=24, barCol="Black", barLoc="Lower Right"):
	imp = IJ.getImage()
	fName = imp.getShortTitle()
	wid = imp.getWidth()
	argThree = "distance=%g known=%f pixel=1 unit=um" % (wid, fwMicrons)
	IJ.run(imp, "Set Scale...", argThree)
	IJ.run(imp, "Enhance Contrast", "saturated=0.35")
	fs = FileSaver(imp) 
	if path.exists(wrkDir) and path.isdir(wrkDir):
		print "folder exists:", wrkDir
		tifName = fName + ".tif"
		tifPath = path.join(wrkDir, tifName)
		print(tifPath)
		if fs.saveAsTiff(tifPath):
			print "Tif saved successfully at ", tifPath  
				
	IJ.run(imp, "RGB Color", "")
	# dummy to get things set
	foo = imp.duplicate()
	s2 = "width=%g height=%g font=%g color=%s location=[%s] bold" % (barWid, barHt, barFnt, barCol, barLoc)
	IJ.run(foo, "Add Scale Bar", s2)
	# explicitly save preferences
	Prefs.savePreferences()
	foo.changes = False
	foo.close()
	IJ.run(imp, "Add Scale Bar", s2)
	fs = FileSaver(imp) 
	pngName = fName + ".png"
	pngPath = path.join(wrkDir, pngName)
	if fs.saveAsPng(pngPath):
		print "png saved successfully at ", pngPath  
def makeStack(stackDir, stackName = "stack"):
    IJ.run("Image Sequence...", "open="+stackDir+" file = (\"img_.*\") sort")
    imp = IJ.getImage()
    #IJ.run("8-bit")
    fs = FileSaver(imp)
    print "Saving stack"
    fs.saveAsTiff(stackDir + "/" +stackName+".tif")
def SaveToZip(zf, ip, baseDir, counter):
	fs = FileSaver(ip)
	fs.setJpegQuality(75)
	fs.saveAsJpeg(baseDir + "/tmp.jpeg")
	zipName = str(counter) + ".jpeg"
	zf.write(baseDir + "/tmp.jpeg", arcname=zipName)
	os.remove(baseDir + "/tmp.jpeg")
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 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)
Example #6
0
def resizeAndSave(filePaths, l):
	while l.get() < min(len(filePaths), currentWrittenLayer + nTilesAtATime + 1) :
		k = l.getAndIncrement()
		if k < min(len(filePaths), currentWrittenLayer + nTilesAtATime):

			filePath = filePaths[k]
			
			imageName = os.path.basename(filePath)
			resizedImageName = os.path.splitext(imageName)[0] + '_resized_' + factorString + os.path.splitext(imageName)[1]
			
			imageFolderName = os.path.basename(os.path.dirname(filePath))
			
			resizedFilePath = fc.cleanLinuxPath(os.path.join(downSampledEMFolder, imageFolderName, resizedImageName))
			
			im = Opener().openImage(filePath)
			IJ.log('Am I going to process the image: im.height = ' + str(im.height) + ' - tileHeight = ' + str(tileHeight) + ' tile number ' + str(k))
			if im.height == tileHeight: # crop a few lines at the top only if it has not already been done (sometimes the pipeline gets rerun)
				im = fc.crop(im,cropRoi)
				im = fc.normLocalContrast(im, normLocalContrastSize, normLocalContrastSize, 3, True, True)
				# IJ.run(im, 'Replace value', 'pattern=0 replacement=1') # only for final waferOverview
				FileSaver(im).saveAsTiff(filePath)
				
			if not os.path.isfile(resizedFilePath):
				im = fc.resize(im, scaleFactor)
				FileSaver(im).saveAsTiff(resizedFilePath)
				IJ.log('Image resized to ' + resizedFilePath)
			im.close()
Example #7
0
def makeStack(stackDir, stackName="stack"):
    IJ.run("Image Sequence...",
           "open=" + stackDir + " file = (\"img_.*\") sort")
    imp = IJ.getImage()
    #IJ.run("8-bit")
    fs = FileSaver(imp)
    print "Saving stack"
    fs.saveAsTiff(stackDir + "/" + stackName + ".tif")
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)
Example #9
0
def straighten(stackName):
    '''
    IJ.run("Set Measurements...", "area mean min center redirect=None decimal=3")
    IJ.open(stackName)
    imp = IJ.getImage()
    stack = imp.getImageStack()

    for i in xrange(1, imp.getNSlices()+1):
        image = ImagePlus(str(i), stack.getProcessor(i))
        xvals = []
        yvals = []
        maxvals = []
        j = 0

        for k in xrange(0, 512, 2):
            IJ.makeRectangle(k, 0, 4, 512)
            IJ.run("Measure")
            table = RT.getResultsTable()

            x = table.getValue("XM", 0)
            y = table.getValue("YM", 0)
            #maxi = IJ.getResult("Max")
            table = []

            xvals.append(k)
            yvals.append(y)
            #maxvals.append(maxi)

            #if maxvals[j] == 0 and j > 0:
                #yvals[j] = yvals[j-1]

            j += 1

        print "xvals:", xvals
        print "yvals:", yvals
        mr = MR()
        IJ.run("Make Selection...", "freeline, "+str(xvals)+" ,"+ str(yvals))

        #IJ.runMacro("makeSelection...", "freeline, "+str(xvals)+" ,"+ str(yvals));

        #IJ.run("makeSelection(\"freeline\", xvals, yvals);")
        #IJ.run("Straighten...", "line = 80")
    '''
    IJ.open(stackName)
    imp = IJ.getImage()
    stack = imp.getImageStack()
    print imp.getNSlices()
    for i in range(1, imp.getNSlices() + 1):
        image = ImagePlus(str(i), stack.getProcessor(i))
        IJ.runMacroFile(
            "/Users/juliansegert/repos/Bio119_root_tracking/straightenOneImage.ijm"
        )
        newImp = WM.getCurrentImage()
        fs = FileSaver(newImp)
        fs.saveAsTiff(
            "/Users/juliansegert/Documents/Roots/Four_root_image_stacks/Pos01/"
            + str(i) + ".tif")
        newImp.close()
def straighten(stackName):
    '''
    IJ.run("Set Measurements...", "area mean min center redirect=None decimal=3")
    IJ.open(stackName)
    imp = IJ.getImage()
    stack = imp.getImageStack()

    for i in xrange(1, imp.getNSlices()+1):
        image = ImagePlus(str(i), stack.getProcessor(i))
        xvals = []
        yvals = []
        maxvals = []
        j = 0

        for k in xrange(0, 512, 2):
            IJ.makeRectangle(k, 0, 4, 512)
            IJ.run("Measure")
            table = RT.getResultsTable()

            x = table.getValue("XM", 0)
            y = table.getValue("YM", 0)
            #maxi = IJ.getResult("Max")
            table = []

            xvals.append(k)
            yvals.append(y)
            #maxvals.append(maxi)

            #if maxvals[j] == 0 and j > 0:
                #yvals[j] = yvals[j-1]

            j += 1

        print "xvals:", xvals
        print "yvals:", yvals
        mr = MR()
        IJ.run("Make Selection...", "freeline, "+str(xvals)+" ,"+ str(yvals))

        #IJ.runMacro("makeSelection...", "freeline, "+str(xvals)+" ,"+ str(yvals));

        #IJ.run("makeSelection(\"freeline\", xvals, yvals);")
        #IJ.run("Straighten...", "line = 80")
    '''
    IJ.open(stackName)
    imp = IJ.getImage()
    stack = imp.getImageStack()
    print imp.getNSlices()
    for i in range(1, imp.getNSlices()+1):
        image = ImagePlus(str(i), stack.getProcessor(i))
        IJ.runMacroFile("/Users/juliansegert/repos/Bio119_root_tracking/straightenOneImage.ijm")
        newImp = WM.getCurrentImage()
    	fs = FileSaver(newImp)
    	fs.saveAsTiff("/Users/juliansegert/Documents/Roots/Four_root_image_stacks/Pos01/"+str(i)+".tif")
    	newImp.close()    
Example #11
0
def covertTo8bitsBatch(folder_in,folder_out):
	for folder in os.listdir(folder_in):
		infolderpath = folder_in+folder
		outfolderpath = folder_out + folder 
		os.mkdir(outfolderpath)
		for filename in os.listdir(infolderpath):
			imp = IJ.openImage(os.path.join(infolderpath, filename))
			IJ.run(imp, "8-bit", "") 
			fs = FileSaver(imp) 
			filepath = os.path.join(outfolderpath, filename)
			fs.saveAsTiff(filepath)
Example #12
0
def save_tif(imps, new_name, new_dir):
    """
	takes imps object and name string, saves as tif
	"""
    new_name = os.path.join(new_dir, new_name)
    if os.path.exists(new_name):
        print("File " + new_name + " exists, continuing")
        return
    else:
        fs = FileSaver(imps)
        fs.saveAsTiff(new_name)
Example #13
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)
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)
def applyFilter(stackName):
    imp = IJ.openImage(stackName)
    stack = imp.getImageStack()

    for i in xrange(1, imp.getNSlices()+1):
        image = ImagePlus(str(i), stack.getProcessor(i))
        IJ.run(image, "Auto Threshold", "method=Li white")

        #IJ.run(image, "Analyze Particles...", "size= 1000-Infinity circularity=0.00-1.00 show=Masks in_situ")
    imp2 = ImagePlus("Threshold", stack)
    fs = FileSaver(imp2)
    print "Saving filtered stack"
    fs.saveAsTiff(stackName[:-4] + "-filtered(Li).tif")
def save_tif(imps, name, new_dir):
	"""
	takes imps object and name string, saves as tif
	"""
	new_name = os.path.join(new_dir, name+".tif")
	if os.path.exists(new_name):
		message = ">> *File:* \n -->"+ new_name + "\n exists, continuing"
		IJ.log(message)
		print("File "+ new_name + " exists, continuing")
		return
	else:
		fs = FileSaver(imps[0])
		fs.saveAsTiff(new_name)
Example #17
0
def applyFilter(stackName):
    imp = IJ.openImage(stackName)
    stack = imp.getImageStack()

    for i in xrange(1, imp.getNSlices() + 1):
        image = ImagePlus(str(i), stack.getProcessor(i))
        IJ.run(image, "Auto Threshold", "method=Li white")

        #IJ.run(image, "Analyze Particles...", "size= 1000-Infinity circularity=0.00-1.00 show=Masks in_situ")
    imp2 = ImagePlus("Threshold", stack)
    fs = FileSaver(imp2)
    print "Saving filtered stack"
    fs.saveAsTiff(stackName[:-4] + "-filtered(Li).tif")
Example #18
0
def stackToSlices(folder_in,folder_out,folder_num):
	for filename in os.listdir(folder_in):  
		imp = IJ.openImage(os.path.join(folder_in, filename))
		stack = imp.getImageStack()
		output=folder_out+str(folder_num)
		folder_num = folder_num+1
		os.makedirs(output)
		for i in xrange(1, imp.getNSlices()+1):
			ip = stack.getProcessor(i)
			imp = ImagePlus("imp", ip)
			fs= FileSaver(imp)
			filepath = os.path.join(output,str(i))
			fs.saveAsTiff(filepath)		
Example #19
0
def saveImage(imp, out_file):
    if overwritePref == overwriteChoices[0]:
        if not os.path.exists(out_file):
            FileSaver(imp).saveAsTiff(out_file)
        else:
            overwriteList.append(out_file)
    elif overwritePref == overwriteChoices[1]:
        if not os.path.exists(out_file):
            FileSaver(imp).saveAsTiff(out_file)

        else:
            overwriteList.append(out_file)
            FileSaver(imp).saveAsTiff(out_file)
Example #20
0
def generate_limit_labels(imp, limits, cb_fraction, params):
    """generate text ROIs in correct positions to label colorbar"""
    rois = []
    w = imp.getWidth()
    h = imp.getHeight()
    txt_h_px = float(h) / 15
    txt_sz_pt = int(round((18.0 / 24.0) * txt_h_px))
    for limit in limits:
        roi = TextRoi(1, 1, str(round(limit, 3)),
                      Font("SansSerif", Font.ITALIC, txt_sz_pt))
        roi.setJustification(TextRoi.RIGHT)
        roi.setFillColor(Color.BLACK)
        roi.setStrokeColor(Color.WHITE)
        rois.append(roi)
    roim = RoiManager(False)
    roim.reset()
    imp.show()
    mbui.autoset_zoom(imp)
    for fridx in range(1, imp.getNSlices() + 1):
        imp.setPosition(fridx)
        roi_uu = rois[1].clone()
        xpos = w - cb_fraction * w - float(w) / 100 - rois[1].getFloatWidth()
        roi_uu.setLocation(xpos, 1)
        imp.setRoi(roi_uu)
        roim.addRoi(roi_uu)
        roi_ll = rois[0].clone()
        roi_ll.setLocation(xpos, h - rois[0].getFloatHeight())
        imp.setRoi(roi_ll)
        roim.addRoi(roi_ll)
    roim.runCommand("Show All")
    FileSaver(imp).saveAsTiff(
        os.path.join(params.output_path,
                     "overlaid curvature nudged labels.tif"))
    # nudge positions
    roim.reset()
    imp.killRoi()
    for fridx in range(1, imp.getNSlices() + 1):
        imp.setPosition(fridx)
        roi_uu = rois[1].clone()
        xpos = w - cb_fraction * w - float(w) / 100
        roi_uu.setLocation(xpos, 1)
        imp.setRoi(roi_uu)
        roim.addRoi(roi_uu)
        roi_ll = rois[0].clone()
        roi_ll.setLocation(xpos, h - rois[0].getFloatHeight())
        imp.setRoi(roi_ll)
        roim.addRoi(roi_ll)
    roim.runCommand("Show All")
    FileSaver(imp).saveAsTiff(
        os.path.join(params.output_path, "overlaid curvature.tif"))
    return imp
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)
Example #22
0
def split_channels_red(imp):
    #Create red channel
    original_red = ChannelSplitter.getChannel(imp, 1)
    original_red_IP = ImagePlus(filename, original_red)
    fs = FileSaver(original_red_IP)
    folder = "/Users/gceleste/Desktop/test/channels"
    filepath = folder + "/" + "{}_redchannel.tif".format(filename)
    fs.saveAsTiff(filepath)
    #Open red channel image.
    red = IJ.open(filepath)
    #red_IP = ImagePlus(filename, red)
    IJ.run(
        "3D Objects Counter",
        "threshold=130 slice=1 min.=50 max.=1447680 exclude_objects_on_edges objects summary"
    )
    #Save red object map.
    red_map = IJ.getImage()
    fs = FileSaver(red_map)
    folder = "/Users/gceleste/Desktop/test/object maps"
    filepath = folder + "/" + "{}_objectmap(red).jpg".format(filename)
    fs.saveAsJpeg(filepath)
    #Close red channel images.
    red_map.close()
    red = IJ.getImage()
    red.close()
Example #23
0
def split_channels_blue(imp):
    #Create blue channel
    original_blue = ChannelSplitter.getChannel(imp, 3)
    original_blue_IP = ImagePlus(filename, original_blue)
    fs = FileSaver(original_blue_IP)
    folder = "/Users/gceleste/Desktop/test/channels"
    filepath = folder + "/" + "{}_bluechannel.tif".format(filename)
    fs.saveAsTiff(filepath)
    #Open blue channel image.
    blue = IJ.open(filepath)
    #blue_IP = ImagePlus(filename, blue)
    IJ.run(
        "3D Objects Counter",
        "threshold=100 slice=1 min.=50 max.=1447680 exclude_objects_on_edges objects summary"
    )
    #Save blue object map
    blue_map = IJ.getImage()
    fs = FileSaver(blue_map)
    folder = "/Users/gceleste/Desktop/test/object maps"
    filepath = folder + "/" + "{}_objectmap(blue).jpg".format(filename)
    fs.saveAsJpeg(filepath)
    #Close blue channel image.
    blue_map.close()
    blue = IJ.getImage()
    blue.close()
Example #24
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
Example #25
0
 def run(self):
     try:
         bounds = self.layer.getMinimalBoundingBox(Patch, True)
         filepath = os.path.join(
             self.target_dir, "section-" + str(self.i).zfill(5) + "-[x=" +
             str(bounds.x) + "-y=" + str(bounds.y) + "-width=" +
             str(bounds.width) + "-height=" + str(bounds.height) + "].zip")
         if os.path.exists(filepath):
             System.out.println("Skipping: " + filepath)
             return
         # Export
         System.out.println("Preparing: " + os.path.split(filepath)[1])
         img = self.layer.getProject().getLoader().getFlatAWTImage(
             self.layer, bounds, 1.0, -1, ImagePlus.GRAY8, Patch, None,
             False, Color.black)
         bi = BufferedImage(img.getWidth(None), img.getHeight(None),
                            BufferedImage.TYPE_BYTE_GRAY)
         g = bi.createGraphics()
         g.drawImage(img, 0, 0, None)
         g.dispose()
         g = None
         imp = ImagePlus(str(self.layer.getZ()), ByteProcessor(bi))
         FileSaver(imp).saveAsZip(filepath)
         bi.flush()
         bi = None
         imp.flush()
         imp = None
         ip = None
         System.out.println("Saved: " + os.path.split(filepath)[1])
     except:
         import sys
         e = sys.exc_info()
         System.out.println("Error:" + str(e[0]) + "\n" + str(e[1]) + "\n" +
                            str(e[2]))
Example #26
0
    def saveCroppedROIs(self, event):
        """ Duplicates cropped ROIs and saves """
        # Create export dir, if not already present
        current_export_dir = self.createExportDir("Cropped_ROI")

        for Image in self.Images.values():  # for all Image instances
            # save image
            cropped_copy = Image.imp.crop()  # returns cropped image as an imp
            img_filename = os.path.join(current_export_dir, Image.title)
            if os.path.splitext(img_filename)[1] != ".tif":
                os.path.join(img_filename, ".tif")
            FileSaver(cropped_copy).saveAsTiff(img_filename)

            # save roi
            roi_filename = os.path.splitext(img_filename)[0] + "_roi.roi"
            roi = Image.imp.getRoi()
            if roi != None:
                rm = RM.getInstance()
                if rm == None:
                    rm = RM()
                rm.addRoi(roi)
                rm.runCommand("Save", roi_filename)  # which one does it save
                rm.runCommand("Delete")
            IJ.log("Cropped ROI saved: " +
                   os.path.join(current_export_dir, Image.title))
Example #27
0
def save_qc_image(imp, rois, output_path):
    """save rois overlaid on imp to output_path"""
    imp.killRoi()
    if len(rois) > 0:
        roim = RoiManager(False)
        for roi in rois:
            roim.addRoi(roi)
        roim.runCommand("Show All with labels")
        RGBStackConverter.convertToRGB(imp)
        roim.moveRoisToOverlay(imp)
        FileSaver(imp).saveAsTiff(output_path)
        roim.runCommand("Show None")
        roim.close()
    else:
        FileSaver(imp).saveAsTiff(output_path)
    return
Example #28
0
def run():
    srcDir = DirectoryChooser("Choose directory").getDirectory()
    if not srcDir:
        return

    targetDir = DirectoryChooser("Choose target directory").getDirectory()
    if targetDir is None:
        # User canceled the dialog
        return

    sId = ".tiff"

    for root, directories, filenames in os.walk(srcDir):
        for filename in filenames:
            path = os.path.join(root, filename)
            if not (sId in filename):
                continue

            cs = ChannelSeparator()
            cs.setId(path)
            print "cs", cs
            bf = BFVirtualStack(path, cs, False, False, False)
            for sliceIndex in xrange(1, bf.getSize() + 1):
                print "Processing slice", sliceIndex
                ip = bf.getProcessor(sliceIndex)
                sliceFileName = os.path.join(targetDir + filename + "_" +
                                             str(sliceIndex) + ".tiff")
                print "writing ", sliceFileName
                FileSaver(ImagePlus(str(sliceIndex),
                                    ip)).saveAsTiff(sliceFileName)
Example #29
0
    def run(self):
        try:
            filepath = self.makeFilePath()
            if os.path.exists(filepath):
                return

            x, y, k = self.coords
            width, height, n_layers = self.dimensions

            # Cube's field of view in XY
            fov = Rectangle(x, y, width, height)

            # Join the bounds of the layers
            r = None
            for b in self.bounds[k:min(k + n_layers, len(bounds))]:
                if r is None:
                    r = Rectangle(b.x, b.y, b.width, b.height)
                else:
                    r.add(b)

            if not fov.intersects(r):
                # Would be empty
                return

            drawImage = Graphics2D.getDeclaredMethod(
                "drawImage", [Image, AffineTransform, ImageObserver])
            drawImage.setAccessible(True)
            dispose = Graphics.getDeclaredMethod("dispose", [])
            dispose.setAccessible(True)

            # Populate and write cube
            stack = ImageStack(width, height)
            for layer in self.layers[k:min(k + n_layers, len(self.layers))]:
                img = layer.getProject().getLoader().getFlatAWTImage(
                    layer, fov, 1.0, -1, ImagePlus.GRAY8, Patch, None, False,
                    Color.black)
                bi = BufferedImage(img.getWidth(None), img.getHeight(None),
                                   BufferedImage.TYPE_BYTE_GRAY)
                g = bi.createGraphics()
                aff = AffineTransform(1, 0, 0, 1, 0, 0)
                #g.drawImage(img, aff, None) # Necessary to bypass issues that result in only using 7-bits and with the ByteProcessor constructor
                drawImage.invoke(g, [img, aff, None])
                #g.dispose()
                dispose.invoke(g, [])
                g = None
                img = None
                stack.addSlice("", ByteProcessor(bi))
                bi.flush()
                bi = None

            imp = ImagePlus("x=%s y=%s k=%s" % (x, y, k), stack)
            Utils.ensure(filepath)
            FileSaver(imp).saveAsZip(filepath)
            imp.flush()
            imp = None
        except:
            e = sys.exc_info()
            System.out.println("Error:" + str(e[0]) + "\n" + str(e[1]) + "\n" +
                               str(e[2]))
            System.out.println(traceback.format_exception(e[0], e[1], e[2]))
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)
def stackToSlices(folder_in,folder_out,folder_num):
	"""Convert a 3D nrrd image to a tiff series"""
	for x in range(14): 
		fnum = folder_num+x
		print(fnum)
		filename = str(fnum)+".nrrd"
		imp = IJ.openImage(os.path.join(folder_in, filename))
		print(os.path.join(folder_in, filename))
		stack = imp.getImageStack()
		output=folder_out+str(fnum)
		os.makedirs(output)
		for i in xrange(1, imp.getNSlices()+1):
			ip = stack.getProcessor(i)
			imp = ImagePlus("imp", ip)
			IJ.run(imp, "8-bit", "") 
			fs= FileSaver(imp)
			filepath = os.path.join(output,str(i)+".tif")
			fs.saveAsTiff(filepath)		
def run(FolderName, SaveFolder):
    # Find tiffiles in folder
    onlyfiles = [f for f in os.listdir(FolderName) if
                 os.path.isfile(os.path.join(FolderName, f)) and f.lower().endswith('.tif')]

    for ii in xrange(0, len(onlyfiles)):
        path = os.path.join(FolderName, onlyfiles[ii])
        print "Processing file..", path

        # Find stimulus, Block, regions from filename for sorting

        # Get all underscores
        underscores = [m.start() for m in re.finditer('_', onlyfiles[ii])]
		
        # Fish Name
        findfish = onlyfiles[ii].find('Fish')
        findunderscore = [i for i in underscores if i > findfish][0]
        fishnum = onlyfiles[ii][findfish:findunderscore]

        print 'Fish Number..', fishnum

        # Block
        findblock = onlyfiles[ii].find('Block')
        findunderscore = [i for i in underscores if i > findblock][0]
        blocknum = onlyfiles[ii][findblock:findunderscore]

        print 'Block Number..', blocknum

        # Stimulus
        findstimulus = onlyfiles[ii].find('Blue')
        findunderscore = [i for i in underscores if i > findstimulus][0]
        stimulustype = onlyfiles[ii][findstimulus:findunderscore]

        print 'Stimulus type..', stimulustype

        # Region
        findregion = onlyfiles[ii].find('Hb')
        findunderscore = [i for i in underscores if i > findregion][0]
        region = onlyfiles[ii][findregion-1:findunderscore]

        print 'Region..', region

        targetDir = os.path.join(SaveFolder, fishnum, region) + filesep
        print 'Images will be saved in .....', targetDir

        if not os.path.exists(targetDir):
            os.makedirs(targetDir)

        cs = ChannelSeparator()
        cs.setId(path)
        bf = BFVirtualStack(path, cs, False, False, False)
        for sliceIndex in xrange(1,bf.getSize() + 1):
            print "Processing slice", sliceIndex
            ip = bf.getProcessor(sliceIndex)
            sliceFileName = os.path.join(targetDir, "T=" + str(sliceIndex) + ".tif")
            FileSaver(ImagePlus(str(sliceIndex), ip)).saveAsTiff(sliceFileName)
def saveFileImage(imagePlus, dumpSaveFilePath, dumpFileName):
    fileSaver = FileSaver(imagePlus)
    imageName = imagePlus.getTitle()
    #File.makeDirectory(dumpDirectory)
    dumpFileString = str(dumpSaveFilePath)+"/"+str(imageName)+"_"+str(dumpFileName)
    #filestring=File.openAsString(dumpFileString);
    #dumpFileString = str(dumpDirectory)
    #fileSaver.saveAsTiff(dumpFileString)
    #IJ.saveAsTiff(imagePlus,dumpFileString)
    IJ.saveAs(imagePlus, "Tiff", dumpFileString);
Example #34
0
def loadProcessAndSave(sourcepath, fn):
  try:
    imp = IJ.openImage(sourcepath)
    norm_imp = fn(imp) # invoke function 'fn', in this case 'normalizeContrast'
    targetpath = os.path.join(targetDir, os.path.basename(sourcepath))
    if not targetpath.endswith(".tif"):
      targetpath += ".tif"
    FileSaver(norm_imp).saveAsTiff(targetpath)
  except:
    print "Could not load or process file:", filepath
    print sys.exc_info()
Example #35
0
def process(srcDir, dstDir, nameContains, currentDir, fileName, keepDirectories, anneBoleyn, overOut):
    print "Opening", fileName
    saveDir = currentDir.replace(srcDir, dstDir) if keepDirectories else dstDir
    head, tail = os.path.splitext(fileName)
    imps = BF.openImagePlus(os.path.join(currentDir, fileName))
    for imp in imps:
        if not anneBoleyn:
            print "Now showing image..."
            imp.show()
        IJ.run(imp, "Blue", "")
    fs = FileSaver(imp)
    if not os.path.exists(saveDir):
        os.makedirs(saveDir)
    if not overOut:
        if os.path.exists(saveDir + "\\" + head + ".jpg"):
            print "This JPG exists already and will not be overwritten. Moving on..."
    else:
        print "Saving to", os.path.join(saveDir, head + ".jpg")
        fs.saveAsJpeg(os.path.join(saveDir, head + ".jpg"))
    imp.close()
def SaveToZip(zf, ip, baseDir, counter):
    fs = FileSaver(ip)
    fs.setJpegQuality(75)
    fs.saveAsJpeg(baseDir + "/tmp.jpeg")
    zipName = str(counter) + ".jpeg"
    zf.write(baseDir + "/tmp.jpeg", arcname=zipName)
    os.remove(baseDir + "/tmp.jpeg")
	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
Example #38
0
def writeZip(img, path, title=""):
  if isinstance(img, RandomAccessibleInterval):
    imp = IL.wrap(img, title)
  elif isinstance(img, ImagePlus):
    imp = img
    if title:
      imp.setTitle(title)
  else:
    syncPrint("Cannot writeZip to %s:\n  Unsupported image type %s" % (path, str(type(img))))
    return None
  #
  FileSaver(imp).saveAsZip(path)
  return imp
	def saveMaxProject(self, destFolder=''):
		channelNumber = 1
		for imp in self.channelImp:
			if not destFolder:
				destFolder = os.path.join(self.enclosingPath, self.enclosingfolder + '_tif', 'max')
			if not os.path.isdir(destFolder):
				os.makedirs(destFolder)

			# make max project
			zp = ZProjector(imp)
			zp.setMethod(ZProjector.MAX_METHOD)
			zp.doProjection()
			zimp = zp.getProjection()

			# save
			saveFile = 'max_' + os.path.splitext(self.filename)[0] + '_ch' + str(channelNumber) + '.tif'
			savePath = os.path.join(destFolder, saveFile)
			fs = FileSaver(zimp)
			bPrintLog('saveMaxProject():' + savePath, 3)
			fs.saveAsTiff(savePath)

			channelNumber += 1
def tstormanlysis(inputfile, csvdatapath, hppath):
    '''
	TSTORMANALYSIS will use predefined parameter for storm analysis in "ThunderSTORM"
	'''

    # set camera
    IJ.run(
        inputfile, "Camera setup",
        "offset=166.0 isemgain=true photons2adu=8.8 gainem=300.0 pixelsize=160.0"
    )

    # run STORM analysis
    IJ.run(inputfile, "Run analysis", (
        "filter=[Wavelet filter (B-Spline)] "
        "scale=2.0 order=3 detector=[Local maximum] connectivity=8-neighbourhood "
        "threshold=std(Wave.F1) estimator=[PSF: Integrated Gaussian] sigma=1.6 "
        "fitradius=3 method=[Weighted Least squares] full_image_fitting=false "
        "mfaenabled=false renderer=[No Renderer]"))
    resultwd = wm.getWindow('ThunderSTORM: results')

    # run drift correction
    IJ.run(
        inputfile, "Show results table",
        ("action=drift magnification=5.0 "
         "method=[Cross correlation] save=false steps=5 showcorrelations=false"
         ))
    driftwd = wm.getWindow('Drift')

    IJ.run(inputfile, "Show results table",
           "action=density neighbors=5 radius=50.0 dimensions=2D")

    IJ.run(inputfile, "Export results",
           ("filepath=[" + csvdatapath + "] "
            "fileformat=[CSV (comma separated)] "
            "sigma=true intensity=true chi2=true "
            "offset=true saveprotocol=true "
            "x=true y=true bkgstd=true "
            "id=true uncertainty=true frame=true"))
    IJ.run(
        inputfile, "Visualization", "imleft=0.0 imtop=0.0 "
        "imwidth=128.0 imheight=128.0 "
        "renderer=[Averaged shifted histograms] "
        "magnification=5.0 colorizez=false threed=false shifts=2")
    imp_histogram = IJ.getImage()
    fs = FileSaver(imp_histogram)
    FileSaverCheck(fs, os.path.dirname(hppath), os.path.basename(hppath))

    # close windows --------------------------------------------------------
    inputfile.close()
    imp_histogram.close()
    driftwd.close()
Example #41
0
def saveFile(imp, format, outputDirPath):
    fs = FileSaver(imp)
    saveDict = {
        'tif': lambda: fs.saveAsTiff(outputDirPath + imp.getTitle() + ".tif"),
        'zip': lambda: fs.saveAsZip(outputDirPath + imp.getTitle() + ".zip"),
        'png': lambda: fs.saveAsPng(outputDirPath + imp.getTitle() + '.png'),
        'txt': lambda: fs.saveAsTxt(outputDirPath + imp.getTitle() + '.txt'),
        'jpg': lambda: fs.saveAsJpg(outputDirPath + imp.getTitle() + '.jpg')
    }

    saveDict[format]()
    return
	def saveMaxProject(self, destFolder=''):
		# ch1
		if self.imp_ch1:
			# make max project
			zp = ZProjector(self.imp_ch1)
			zp.setMethod(ZProjector.MAX_METHOD)
			zp.doProjection()
			zimp = zp.getProjection()

			# save
			fs = FileSaver(zimp)
			bPrintLog('saveMaxProject():' + self.savePathMax_ch1, 3)
			fs.saveAsTiff(self.savePathMax_ch1)
		# ch2
		if self.imp_ch2:
			# make max project
			zp = ZProjector(self.imp_ch2)
			zp.setMethod(ZProjector.MAX_METHOD)
			zp.doProjection()
			zimp = zp.getProjection()

			# save
			fs = FileSaver(zimp)
			bPrintLog('saveMaxProject():' + self.savePathMax_ch2, 3)
			fs.saveAsTiff(self.savePathMax_ch2)
		# ch1
		if self.imp_ch3:
			# make max project
			zp = ZProjector(self.imp_ch3)
			zp.setMethod(ZProjector.MAX_METHOD)
			zp.doProjection()
			zimp = zp.getProjection()

			# save
			fs = FileSaver(zimp)
			bPrintLog('saveMaxProject():' + self.savePathMax_ch3, 3)
			fs.saveAsTiff(self.savePathMax_ch3)
	if chosenData < 9 and applyNucleiCropping == 1:
		imageNPath = nucleiFolder + digit + appendix
		imageNCroppedPath = cropNucleiOutput + digit + appendix
	
		print 'Opening image', imageNPath
		impN = IJ.openImage( imageNPath )
		impN.setRoi( ROI_xStart, ROI_yStart, ROI_xSize, ROI_ySize )
		slices = impN.getNSlices()
		if ROI_zSize == 0:
			ROI_zSize = slices
		stack = impN.getStack()
		# crop(int x, int y, int z, int width, int height, int depth)
		impN.setStack( stack.crop( ROI_xStart, ROI_yStart, ROI_zStart, ROI_xSize, ROI_ySize, ROI_zSize ) )
		#impN.setStack( stack.crop( ROI_xStart, ROI_yStart, 130, ROI_xSize, ROI_ySize, 220 ) )
		#impN.setStack( stack.crop( ROI_xStart, ROI_yStart, 275, ROI_xSize, ROI_ySize, 1 ) )
		fs = FileSaver( impN )
		fs.saveAsTiff( imageNCroppedPath )
	
		zp = ZProjector(impN)
		zp.setMethod( ZProjector.MAX_METHOD )
		zp.doProjection()
		MIPimpN = zp.getProjection()
		#MIPimpN.show()

	if applyMembraneCropping == 1:
		imageMPath = membraneFolder + digit + appendix
		imageMCroppedPath = cropMembraneOutput + digit + appendix
	
		print 'Opening image', imageMPath
		impM = IJ.openImage( imageMPath )
		impM.setRoi( ROI_xStart, ROI_yStart, ROI_xSize, ROI_ySize )
Example #44
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"
import sys
sys.path.append("/Users/berthola/Desktop/Fiji Scripts")
from matrixoperator import Matrix
from javax.media.j3d import Transform3D
from javax.vecmath import Point3d
from ij.io import FileSaver
from profilingFixedCoordinates import getDendriticProfiles
from profilingFixedCoordinates import getNodeCoordinates
from machine_ import featureVector



good = featureVector(72481, 99481, 50)
bad =  featureVector(83160, 99481, 50)





plot = Plot("histogram", "y-coordinates", "count",range(0, 50), good)
plot.setLimits(0.0, 50.0, 0, 60000000.0) 
plot.show()
fs=FileSaver(plot.getImagePlus())
fs.saveAsPng(System.getProperty("user.home") + "/Desktop/Histotest/y" + "good.png")

plot = Plot("histogram", "y-coordinates", "count",range(0, 50), bad)
plot.setLimits(0.0, 50.0, 0, 60000000.0) 
plot.show()
fs=FileSaver(plot.getImagePlus())
fs.saveAsPng(System.getProperty("user.home") + "/Desktop/Histotest/y" + "bad.png")
Example #46
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()
Example #47
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)
Example #48
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")
IJ.open(imgPath);
IJ.run("Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.03143555 pixel_height=0.03144531 voxel_depth=1.0000000");
orig = IJ.getImage();

ti = orig.getShortTitle();
pngPath = homDir + relDir + "/" + ti + ".png"

strBar = "width=%g height=%g font=%g color=%s location=[%s] bold" % (barW, barH, barF, barC, barL)
# a hack to get the scale bars to work reliably
IJ.run(orig, "RGB Color", "")

# dummy to get things set
foo = orig.duplicate()
IJ.run(foo, "Add Scale Bar", strBar)
# explicitly save preferences
Prefs.savePreferences()
foo.changes = False
foo.close()

IJ.run(orig, "Add Scale Bar", strBar)
print(pngPath)

fs = FileSaver(orig)
if fs.saveAsPng(pngPath):
	print "png saved successfully at ", pngPath  

time.sleep(sleepTime)

orig.close()
  #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()

Example #51
0
labId = "qm-04513"
smpId = "RAD-2015-0148Y-HCl-xs"

datDir	 = edsDir + "/Oxford/" + ePrjDir + "/reports/" + labId + "-" + smpId
sTifPath = datDir + "/tif/"

bSetMinMax = False
gMin =  1000
gMax = 11400
fwUnits = 28.9


units = IJ.micronSymbol + "m"

imp = IJ.getImage()
imp = jmg.calibImage(imp, fwUnits, units=-6)
if(bSetMinMax == True):
	IJ.setMinAndMax(gMin, gMax)
imp.updateAndRepaintWindow()

ti = imp.getShortTitle()
fi = sTifPath + ti + ".tif"
fs = FileSaver(imp)
imp.changes = False
print(fi)
if fs.saveAsTiff(fi):
	print "Tif saved successfully at ", fi  


print("done")
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)
			mu = IJ.micronSymbol
			strUnits = mu + "m"
			fScaleX /= 1000.
			fScaleY /= 1000.	
			
		imp = IJ.openImage(strPath)
		cal = imp.getCalibration()
		cal.setXUnit(strUnits)
		cal.setYUnit(strUnits)
		cal.pixelWidth = fScaleX
		cal.pixelHeight = fScaleY
		imp.show()
		time.sleep(1)

		imp.changes = False
		fs = FileSaver(imp)
		if fs.saveAsTiff(strPath):
			print "Tif saved successfully at ", strPath
		
		
		imp.close()
		
		print(strUnits)
		# print(row[3])



print("done")


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()
# testHeadlessCrop_.py
#
# load and crop an image in headless mode
from org.python.core import codecs
codecs.setDefaultEncoding('utf-8')

import os
from ij import IJ
from ij.io import FileSaver

gitDir = os.environ['GIT_HOME']
relImg = "/OSImageAnalysis/images"
imgPath = gitDir + relImg + "/latex.tif"

delta = 32
imp = IJ.openImage(imgPath)
name = imp.getShortTitle()
w = imp.getWidth()
h = imp.getHeight()
imp.setRoi(delta,delta,w-(2*delta),h-(2*delta))
IJ.run(imp,"Crop","")

imgPath = gitDir + relImg + "/%s-cr.tif" % name

fs = FileSaver(imp) 
fs.saveAsTiff(imgPath) 



	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)
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
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 "   ==="
	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()
Example #60
0
files = [f for f in files if ".tif" in f]
for f in files:
    imp = IJ.openImage(rootdir + f)
    ip = imp.getProcessor().convertToFloat()
    pixels = ip.getPixels()
    thresh = 800  # reduce(max,pixels)

    def ffun(x):
        if (x * 4000 / thresh) > 3000:
            return 3000
        else:
            return x * 4000 / thresh

    newpixels = map(ffun, pixels)
    ip2 = FloatProcessor(ip.width, ip.height, newpixels, None)
    print f
    ip2.setInterpolationMethod(2)
    ip2 = ip2.resize(ip.width / 2, ip.height / 2, True)
    imp2 = ip2.createImage()
    imp2 = ImagePlus(imp.title, imp2)
    fs = FileSaver(imp2)
    fs.saveAsTiff(outroot + f[:-3] + "down.tif")
    imp.close()
    imp2.close()
    del (imp)
    del (imp2)
    del (ip2)
    del (newpixels)
    del (pixels)
    del (ip)