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 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
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()
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()
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)
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 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 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)
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)
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)
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 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)
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)
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 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 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
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 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 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=''): 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 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 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 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 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)
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)
elif i < 1000: digit = str(i) imagePath = sourceFolder + digit + appendix outputPath = outputFolder + digit + '.tif' # open image file print 'Opening image', imagePath imp = IJ.openImage( imagePath ) slices = imp.getNSlices() stack1 = imp.getStack() stack2 = IMGS( imp.getWidth(), imp.getHeight() ) print 'Normalizing image...' for s in range( 0, slices ): ip = stack1.getProcessor(s+1) for x in range( 0, imp.getWidth() ): for y in range( 0, imp.getHeight() ): oldI = ip.get( x, y ) newI = 65535 * (oldI - minI)/(maxI - minI) newI = int(newI) ip.set( x, y, newI ) label = stack1.getSliceLabel(s+1) ip.resetMinAndMax() stack2.addSlice( label, ip ) IJ.showProgress(s+1, slices) imp.setStack( stack2 ) fs = FileSaver( imp ) print "Saving to", outputPath fs.saveAsTiff( outputPath )
# 파일 이름 지정해서 저장 from ij import IJ from ij.io import FileSaver imp = IJ.getImage() fs = FileSaver(imp) # image가 파일로 지정될 폴더 folder = "C:\Arbeitplatz\03_ImageJ_script_learning\sample_code\images" # \ 가 에러 유발 filepath = folder + "\" + "boats.tif" print filepath fs.saveAsTiff(filepath)
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)
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 ) slices = impM.getNSlices()
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)
for fn in ['0', '1']: filename = os.environ['HOME'] + '/' + basename + '_' + fn + '.pgm' imp = IJ.openImage(filename) if imp is None: print "Could not open image from file:", filename frame.append(imp) print 'loaded frames' width = frame[0].width height = frame[0].height bpix = zeros('h', (width + height)**2) for fn in [0, 1]: pix = frame[fn].getProcessor().getPixels() for i in range(len(pix)): x = i % width + i / width + fn # the second frame (fn == 1) is shifted 1px to the right y = (width - i % width - 1) + (i / width) bpix[y * (width + height) + x] = pix[i] print 'wrote frame %s' % fn ip = ShortProcessor(width + height, width + height, bpix, None) bayer = ImagePlus("Sensor", ip) fs = FileSaver(bayer) fs.saveAsTiff(os.path.dirname(filename) + '/' + 'raw.tiff') print '/opt/local/bin/tiffset' + ' -s' + ' 270' + ' width = ' + str(width) + ', height = ' + str(height) + ' ' + os.environ['HOME'] + '/test/' + 'raw.tiff' subprocess.call(['/opt/local/bin/tiffset', '-s', '270', 'width = ' + str(width) + ', height = ' + str(height), os.environ['HOME'] + '/test/' + 'raw.tiff']) bayer.show()
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()
def loadStacks(): IJ.log(" ") IJ.log( "oib concatenator v0.5.1; 2012; [email protected]; [email protected]; revised by [email protected]" ) IJ.log("tested with: ImageJ 1.47a; FIJI update on July 20th 2012") srcDir = DirectoryChooser("Choose directory").getDirectory() if not srcDir: return sId = ".oib" #stackType = getChoice("", ["normal stack", "virtual stack"]) stackType = "normal stack" # Concatenate seems not to work with virtual #filepath = srcDir +"tiff" #print(filepath) iStack = 0 for root, directories, filenames in os.walk(srcDir): for filename in filenames: path = os.path.join(root, filename) if not (sId in filename): continue IJ.log("opening " + filename) if stackType == "virtual stack": IJ.run( "Bio-Formats Importer", "open=" + path + " color_mode=Default view=[Standard ImageJ] stack_order=Default use_virtual_stack" ) else: IJ.run( "Bio-Formats Importer", "open=" + path + " color_mode=Default view=[Standard ImageJ] stack_order=Default" ) # first stack if iStack == 0: imp = IJ.getImage() imp.setTitle( filename + ".tiff") # in order of the combining to work additive nSlices = imp.getNSlices() nChannels = imp.getNChannels() nTimeFrames = imp.getNFrames() #IJ.run("Stack to Hyperstack...", "order=xyczt(default) channels="+str(nChannels)+" slices="+str(nSlices)+" frames="+str(nTimeFrames)+" display=Color"); #IJ.log("convert back to normal stack: Image...Hyperstacks...Hyperstack to Stack") fs = FileSaver(imp) fs.saveAsTiff(srcDir + filename + ".tiff") else: imp = IJ.getImage() imp.setTitle( filename + ".tiff") # in order of the combining to work additive #IJ.run(imp,"Concatenate...", "image1=stack image2=st2 title=[stack]"); #IJ.run("Stack to Hyperstack...", "order=xyczt(default) channels="+str(nChannels)+" slices="+str(nSlices)+" frames="+str(nTimeFrames)+" display=Color"); #IJ.log("convert back to normal stack: Image...Hyperstacks...Hyperstack to Stack") fs = FileSaver(imp) fs.saveAsTiff(srcDir + filename + ".tiff") iStack = iStack + 1 print(iStack) IJ.log("nChannels = " + str(nChannels)) IJ.log("nSlices = " + str(nSlices)) IJ.log("nFrames = " + str(nTimeFrames * iStack)) #IJ.run("Stack to Hyperstack...", "order=xyczt(default) channels="+str(nChannels)+" slices="+str(nSlices)+" frames="+str(nTimeFrames)+" display=Color"); IJ.log( "convert back to normal stack: Image...Hyperstacks...Hyperstack to Stack" ) IJ.log( "if you got an error message from the hyperstack you probably ran out of memory and it did not load all files!" )
def import_and_straighten(imgDir): """ Core function. Opens images in given directory in series and calls a straightening function. Thresholds using weka if stddev of pixel intensities is too high (bright field), otherwise uses histogram based segmentation. """ targetWidth = 800 #adjustable make_directory(imgDir) index = "000000000" filename = imgDir + "/img_" + index + "__000.tif" if path.exists(filename): weka = Weka_segmentor(IJ.openImage(filename)) while path.exists(filename): IJ.run("Set Measurements...", "mean standard min center redirect=None decimal=3") IJ.run("Clear Results") imp = IJ.openImage(filename) imp.show() IJ.run("Rotate 90 Degrees Left") IJ.run("Measure") table = RT.getResultsTable() stddev = RT.getValue(table, "StdDev", 0) if stddev < 20: segmented = weka.getThreshold(imp) segmented.show() IJ.run("8-bit") IJ.run("Invert") imp.close() imp = segmented else: IJ.run(imp, "Auto Threshold", "method=Li white") #threshold imp = preProcess_(imp) #straighten_roi_rotation() coords = run_straighten() newImp = IJ.getImage() """ fs = FileSaver(newImp) fs.saveAsTiff(imgDir + "/straightened" + "/img_" + index + "__000-straight.tif") """ IJ.run("Image Padder", "pad_right=" + str(targetWidth - newImp.getWidth())) paddedImp = IJ.getImage() fs = FileSaver(paddedImp) fs.saveAsTiff(imgDir + "/binary" + "/img_" + index + "__000-padded.tif") IJ.runMacro("while (nImages>0) {selectImage(nImages);close();}") #use same centerline for original greyscale image imp = IJ.openImage(filename) imp.show() IJ.run("Rotate 90 Degrees Left") IJ.run("8-bit") IJ.runMacro("makeLine(" + coords + ")") IJ.run("Straighten...", "line = 80") newImp = IJ.getImage() IJ.run("Image Padder", "pad_right=" + str(targetWidth - newImp.getWidth())) paddedImp = IJ.getImage() IJ.run("8-bit") fs = FileSaver(paddedImp) fs.saveAsTiff(imgDir + "/greyscale" + "/img_" + index + "__000-padded.tif") IJ.runMacro("while (nImages>0) {selectImage(nImages);close();}") index = to_9_Digits(str(int(index) + 1)) filename = filename = imgDir + "/img_" + index + "__000.tif"
def call(self, save_images=False): self.thread_used = threading.currentThread().getName() self.started = time.time() try: filenames = os.listdir(self.params.input_folder) filenames.sort() imp1 = IJ.openImage(os.path.join(self.params.input_folder, filenames[self.imgA])) imp2 = IJ.openImage(os.path.join(self.params.input_folder, filenames[self.imgB])) IJ.log(time.asctime()) IJ.log(str(self.imgA) + ": " + str(imp1)) IJ.log(str(self.imgB) + ": " + str(imp2)) print str(self.imgA) + ": " + str(imp1) print str(self.imgB) + ": " + str(imp2) mesh_resolution = int(imp1.getWidth() / self.params.point_distance) effective_point_distance = imp1.getWidth() / mesh_resolution mesh = SpringMesh(mesh_resolution, imp1.getWidth(), imp1.getHeight(), 1, 1000, 0.9) vertices = mesh.getVertices() maskSamples = RealPointSampleList(2) for vertex in vertices: maskSamples.add(RealPoint(vertex.getL()), ARGBType(-1)) # equivalent of 0xffffffff pm12 = ArrayList() v1 = mesh.getVertices() ip1 = imp1.getProcessor().convertToFloat().duplicate() ip2 = imp2.getProcessor().convertToFloat().duplicate() ip1Mask = self.createMask(imp1.getProcessor().convertToRGB()) ip2Mask = self.createMask(imp2.getProcessor().convertToRGB()) ct = TranslationModel2D() BlockMatching.matchByMaximalPMCC( ip1, ip2, ip1Mask, ip2Mask, self.params.scale, ct, self.params.block_radius, self.params.block_radius, self.params.search_radius, self.params.search_radius, self.params.min_R, self.params.rod_R, self.params.max_curvature_R, v1, pm12, ErrorStatistic(1)) pre_smooth_block_matches = len(pm12) if self.params.save_data: pre_smooth_filename = self.params.output_folder + str(imp2.getTitle())[:-4] + "_" + str(imp1.getTitle())[:-4] + "_pre_smooth_pts.txt" self.writePointsFile(pm12, pre_smooth_filename) if self.params.use_local_smoothness_filter: model = Util.createModel(self.params.local_model_index) try: model.localSmoothnessFilter(pm12, pm12, self.params.local_region_sigma, self.params.max_local_epsilon, self.params.max_local_trust) if self.params.save_data: post_smooth_filename = self.params.output_folder + str(imp2.getTitle())[:-4] + "_" + str(imp1.getTitle())[:-4] + "_post_smooth_pts.txt" self.writePointsFile(pm12, post_smooth_filename) except: pm12.clear() color_samples, max_displacement = self.matches2ColorSamples(pm12) post_smooth_block_matches = len(pm12) print time.asctime() print str(self.imgB) + "_" + str(self.imgA) + "\tblock_matches\t" + str(pre_smooth_block_matches) + "\tsmooth_filtered\t" + str(pre_smooth_block_matches - post_smooth_block_matches) + "\tmax_displacement\t" + str(max_displacement) + "\trelaxed_length\t" + str(effective_point_distance) + "\tsigma\t" + str(self.params.local_region_sigma) IJ.log(time.asctime()) IJ.log(str(self.imgB) + "_" + str(self.imgA) + ": block_matches " + str(pre_smooth_block_matches) + ", smooth_filtered " + str(pre_smooth_block_matches - post_smooth_block_matches) + ", max_displacement " + str(max_displacement) + ", relaxed_length " + str(effective_point_distance) + ", sigma " + str(self.params.local_region_sigma)) if self.params.save_data and self.wf: self.wf.write(str(self.imgB) + "\t" + str(self.imgA) + "\t" + str(imp2.getTitle())[:-4] + "\t" + str(imp1.getTitle())[:-4] + "\t" + str(pre_smooth_block_matches) + "\t" + str(pre_smooth_block_matches - post_smooth_block_matches) + "\t" + str(max_displacement) + "\t" + str(effective_point_distance) + "\t" + str(self.params.local_region_sigma) + "\t" + str(mesh_resolution) + "\n") if self.params.export_point_roi: pm12Sources = ArrayList() pm12Targets = ArrayList() PointMatch.sourcePoints(pm12, pm12Sources) PointMatch.targetPoints(pm12, pm12Targets) roi1 = pointsToPointRoi(pm12Sources) roi2 = pointsToPointRoi(pm12Targets) imp1.setRoi(roi1) imp2.setRoi(roi2) if self.params.export_displacement_vectors: pm12Targets = ArrayList() PointMatch.targetPoints(pm12, pm12Targets) maskSamples2 = RealPointSampleList(2) for point in pm12Targets: maskSamples2.add(RealPoint(point.getW()), ARGBType(-1)) factory = ImagePlusImgFactory() kdtreeMatches = KDTree(color_samples) kdtreeMask = KDTree(maskSamples) img = factory.create([imp1.getWidth(), imp1.getHeight()], ARGBType()) self.drawNearestNeighbor( img, NearestNeighborSearchOnKDTree(kdtreeMatches), NearestNeighborSearchOnKDTree(kdtreeMask)) scaled_img = self.scaleIntImagePlus(img, 0.1) if self.params.save_data: fs = FileSaver(scaled_img) fs.saveAsTiff(self.params.output_folder + str(imp2.getTitle())[:-4] + "_" + str(imp1.getTitle())) else: scaled_img.show() print time.asctime() print str(self.imgB) + "_" + str(self.imgA) + "\tsaved\t" + filenames[self.imgB] IJ.log(time.asctime()) IJ.log(str(self.imgB) + "_" + str(self.imgA) + ": saved " + filenames[self.imgB]) except Exception, ex: self.exception = ex print str(ex) IJ.log(str(ex)) if self.params.save_data and self.wf: self.wf.write(str(ex) + "\n")
def run_script(): print('Print Script Parameter') print('path: {}'.format(path_j)) print('dir_output: {}'.format(dir_output)) print('ippath: {}'.format(ippath_j)) print('op_bi_path: {}'.format(op_bi_path_j)) print('op_data_path: {}'.format(op_data_path_j)) print(batchmodeop) path = str(path_j) ippath = str(ippath_j) op_bi_path = str(op_bi_path_j) op_data_path = str(op_data_path_j) print('Preparing ...') import gc if batchmodeop: Interpreter.batchMode = True nchannels = 2 dir_check = [] # create output path for c in range(nchannels): dir_check.append(os.path.join(op_bi_path, str(c+1))) dir_check.append(os.path.join(op_data_path, str(c+1))) dircheck(dir_check) # create the pending file list ------------------------------------------ # pendingfllist = [] pendingpathlist_ip = [] pendingpathlist_op_data = [] pendingpathlist_op_bi = [] # return the pending files ------------------------------------------ # filelist = {} filenamelist = listfiles(os.path.join(ippath, '1'), '.tif')['filelist'] filedir = ['ip_filename', 'ip_path', 'op_data', 'op_bi'] treatment = ['wildtype', 'knockout'] # group the data by the treatment ------------------------------------------ # for c in range(nchannels): filelist[str(c+1)] = {} for group in treatment: filelist[str(c+1)][group] = {} # create list filelist_temp = [] for l in filenamelist: if group == 'wildtype': x = re.search('(.*)_w{1}[0-9]{1}_(.*)', l) else: x = re.search('(.*)_k{1}[0-9]{1}_(.*)', l) try: found = x.group(0) filelist_temp.append(found) except AttributeError: found = '' ip_filepath = [] op_bi_filepath = [] op_data_filepath = [] for f in filelist_temp: ip_filepath_tmp = os.path.join(ippath, str(c+1), f) ip_filepath.append(ip_filepath_tmp) op_data_filepath_temp = os.path.join(op_data_path, str(c+1), f.replace('.tif', '.csv')) op_data_filepath.append(op_data_filepath_temp) op_bi_filepath_temp = os.path.join(op_bi_path, str(c+1), f) op_bi_filepath.append(op_bi_filepath_temp) filelist[str(c+1)][group][filedir[0]] = filelist_temp filelist[str(c+1)][group][filedir[1]] = ip_filepath filelist[str(c+1)][group][filedir[2]] = op_bi_filepath filelist[str(c+1)][group][filedir[3]] = op_data_filepath pprint.pprint(filelist) # image processing ------------------------------------------ # threshold_c = {'1': 300, '2': 100} for c in range(nchannels): for group in treatment: for i in range(len(filelist[str(c+1)][group][filedir[0]])): # open image ipfilepath_tmp = filelist[str(c+1)][group][filedir[1]][i] op_bi_filepath_tmp = filelist[str(c+1)][group][filedir[2]][i] op_data_filepath_tmp = filelist[str(c+1)][group][filedir[3]][i] print(ipfilepath_tmp) print(op_bi_filepath_tmp) print(op_data_filepath_tmp) imp = IJ.openImage(ipfilepath_tmp) imp.show() IJ.setThreshold(threshold_c[str(c+1)], 5000) IJ.run(imp, "Convert to Mask", "") IJ.run(imp, "Set Measurements...", "area mean standard modal min centroid center perimeter bounding fit shape feret's integrated median skewness kurtosis area_fraction stack redirect=None decimal=9") IJ.run(imp, "Analyze Particles...", "size=0-Infinity show=Masks display exclude clear") # save binary imp_bi = IJ.getImage() fs = FileSaver(imp_bi) fs.saveAsTiff(op_bi_filepath_tmp) imp_bi.close() # save results biresults = wm.getWindow("Results") wm.setWindow(biresults) IJ.saveAs("Results", op_data_filepath_tmp) if not biresults is None: biresults.close() imp.close() if batchmodeop: Interpreter.batchMode = False return
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)
def loadStacks(): IJ.log(" ") IJ.log("oib_tiff_converter_ver1.0; 08/24/2018; [email protected]") IJ.log("tested with: ImageJ2; FIJI update on 8/24/2018") srcDir = DirectoryChooser("Choose directory").getDirectory() if not srcDir: return sId = ".oib" #stackType = getChoice("", ["normal stack", "virtual stack"]) stackType = "normal stack" # Concatenate seems not to work with virtual #filepath = srcDir +"tiff" #print(filepath) iStack = 0 for root, directories, filenames in os.walk(srcDir): for filename in filenames: path = os.path.join(root, filename) if not (sId in filename): continue IJ.log("opening " + filename) if stackType == "virtual stack": IJ.run( "Bio-Formats Importer", "open=" + path + " color_mode=Default view=[Standard ImageJ] stack_order=Default use_virtual_stack" ) else: IJ.run( "Bio-Formats Importer", "open=" + path + " color_mode=Default view=[Standard ImageJ] stack_order=Default" ) # first stack if iStack == 0: imp = IJ.getImage() imp.setTitle( filename + ".tiff") # in order of the combining to work additive nSlices = imp.getNSlices() nChannels = imp.getNChannels() nTimeFrames = imp.getNFrames() imp.setDimensions(nChannels, nSlices, nTimeFrames) comp = CompositeImage(imp, CompositeImage.COLOR) comp.show() fs = FileSaver(comp) fs.saveAsTiff(srcDir + filename + "_hyperstack" + ".tiff") else: imp = IJ.getImage() comp = CompositeImage(imp, CompositeImage.COLOR) comp.show() fs = FileSaver(comp) fs.saveAsTiff(srcDir + filename + "_hyperstack" + ".tiff") iStack = iStack + 1 print(iStack) #IJ.log("nChannels = "+str(nChannels)) #IJ.log("nSlices = "+str(nSlices)) #IJ.log("nFrames = "+str(nTimeFrames*iStack)) #IJ.run("Stack to Hyperstack...", "order=xyczt(default) channels="+str(nChannels)+" slices="+str(nSlices)+" frames="+str(nTimeFrames)+" display=Color"); IJ.log( "convert back to normal stack: Image...Hyperstacks...Hyperstack to Stack" )
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)
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()
# 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)
ip = EM.getProcessor() width = ip.getWidth() height = ip.getHeight() EM.setProcessor(EM.getTitle(), EM.getProcessor().resize(256, 256)) ImageConverter(EM).convertToGray8() # create stack z=2 EMstack = ImageStack(EM.getWidth(), EM.getHeight()) EMstack.addSlice(str(1), EM.getProcessor()) EMstack.addSlice(str(2), EM.getProcessor()) EM = ImagePlus(EM.getTitle(), EMstack) # save EM image saveEMfilepath = os.path.join(workdir, "EM.tif") fs = FileSaver(EM) fs.saveAsTiff(saveEMfilepath) print("(- )preprocessing done") ############################################ predict image # use plugin CSBDeep (https://github.com/CSBDeep/CSBDeep_fiji/blob/master/script/CARE_generic.py) # create path to save pLM image savepLMfilepath = os.path.join(workdir, "registration_input", "pLM.tif") # define some parameters nTiles = 16 overlap = 32 normalizeInput = True percentileBottom = 0.5
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
files.sort() 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)
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")
from sys import argv stackDir = argv[1] #IJ.run("Image Sequence...", "open="+stackDir+" sort") imp = IJ.openImage(stackDir + "/stack.tif") stack = imp.getImageStack() print "Number of slices:", imp.getNSlices() for i in xrange(1, imp.getNSlices()): print i image = stack.getProcessor(i) IJ.run(ImagePlus(str(i), image), "Auto Threshold", "method=Default white") imp2 = ImagePlus("Threshold", stack) fs = FileSaver(imp2) fs.saveAsTiff(stackDir + "/Filtered.tif") """ #in case you want to make a stack from a folder imp = IJ.getImage() #stack = imp.getImageStack() fs = FileSaver(imp) fs.saveAsTiff(stackDir + "/stack.tif") #print "Number of slices:", stack.getNSlices() #imp = IJ.openImage(argv[1]) #first command line arg is file directory #print imp.title """
print("order=xyczt(default) channels=2 slices="+ str(z_slices) + " frames=1 display=Color", image.getDimensions()) image_two = HyperStackConverter.toHyperStack(image,2,z_slices,1) image = CompositeImage(image_two) image.show() rt = run_comdet(image) rt.save(directory+"/"+filename+"_results.csv" ) image = IJ.getImage() if auto_cell: mask = generate_mask(image_green, auto_cell_thresh) fs = FileSaver(mask) filepath = directory + "/" + filename + "_mask.tiff" fs.saveAsTiff(filepath) rest = ResultsTable.open(directory+"/"+filename+"_results.csv") #print(rest.getColumnHeadings()) remove_outside_cell(rest,mask) rest.save(directory+"/"+filename+"_results.csv" ) else: rest = rt image.setDimensions(2, z_slices, 1)
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 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 call(self, save_images=False): self.thread_used = threading.currentThread().getName() self.started = time.time() try: IJ.log(time.asctime()) IJ.log(str(self.patchA)) IJ.log(str(self.patchB)) print str(self.patchA) print str(self.patchB) # Adapted from ElasticMontage.java # https://github.com/trakem2/TrakEM2/blob/master/TrakEM2_/src/main/java/mpicbg/trakem2/align/ElasticMontage.java pi1 = self.patchA.createTransformedImage() pi2 = self.patchB.createTransformedImage() fp1 = pi1.target.convertToFloat() mask1 = pi1.getMask() if mask1 is None: fpMask1 = None else: fpMask1 = scaleByte(mask1) fp2 = pi2.target.convertToFloat() mask2 = pi2.getMask() if mask2 is None: fpMask2 = None else: fpMask2 = scaleByte(mask1) w = self.tileA.getWidth() h = self.tileA.getHeight() num_x = Math.max(2, int(Math.ceil(w / self.params.spring_length) + 1)) num_y = Math.max(2, int(Math.ceil(h / self.params.spring_triangle_height_twice) + 1)) w_mesh = (num_x - 1) * self.params.spring_length h_mesh = (num_y - 1) * self.params.spring_triangle_height_twice mesh = SpringMesh(num_x, num_y, w_mesh, h_mesh, self.params.stiffness, self.params.max_stretch * self.params.scale, self.params.damp) vertices = mesh.getVertices() maskSamples = RealPointSampleList(2) for vertex in vertices: maskSamples.add(RealPoint(vertex.getL()), ARGBType(-1)) # equivalent of 0xffffffff pm12 = ArrayList() v1 = mesh.getVertices() t = self.tileB.getModel().createInverse() t.concatenate(self.tileA.getModel()) BlockMatching.matchByMaximalPMCC( fp1, fp2, fpMask1, fpMask2, self.params.scale, t, self.params.block_radius, self.params.block_radius, self.params.search_radius, self.params.search_radius, self.params.min_R, self.params.rod_R, self.params.max_curvature_R, v1, pm12, ErrorStatistic(1)) pre_smooth_block_matches = len(pm12) if self.params.save_data: pre_smooth_filename = self.params.output_folder + str(self.patchB) + "_" + str(self.patchA) + "_pre_smooth_pts.txt" self.writePointsFile(pm12, pre_smooth_filename) if self.params.use_local_smoothness_filter: model = Util.createModel(self.params.local_model_index) try: model.localSmoothnessFilter(pm12, pm12, self.params.local_region_sigma, self.params.max_local_epsilon, self.params.max_local_trust) if self.params.save_data: post_smooth_filename = self.params.output_folder + str(self.patchB) + "_" + str(self.patchA) + "_post_smooth_pts.txt" self.writePointsFile(pm12, post_smooth_filename) except: pm12.clear() color_samples, max_displacement = self.matches2ColorSamples(pm12) post_smooth_block_matches = len(pm12) print time.asctime() print str(self.patchB) + "_" + str(self.patchA) + "\tblock_matches\t" + str(pre_smooth_block_matches) + "\tsmooth_filtered\t" + str(pre_smooth_block_matches - post_smooth_block_matches) + "\tmax_displacement\t" + str(max_displacement) + "\trelaxed_length\t" + str(self.params.spring_length) + "\tsigma\t" + str(self.params.local_region_sigma) IJ.log(time.asctime()) IJ.log(str(self.patchB) + "_" + str(self.patchA) + ": block_matches " + str(pre_smooth_block_matches) + ", smooth_filtered " + str(pre_smooth_block_matches - post_smooth_block_matches) + ", max_displacement " + str(max_displacement) + ", relaxed_length " + str(self.params.spring_length) + ", sigma " + str(self.params.local_region_sigma)) if self.params.save_data and self.wf: self.wf.write(str(self.patchB) + "\t" + str(self.patchA) + "\t" + str(pre_smooth_block_matches) + "\t" + str(pre_smooth_block_matches - post_smooth_block_matches) + "\t" + str(max_displacement) + "\t" + str(self.params.spring_length) + "\t" + str(self.params.local_region_sigma) + "\t" + str(num_x) + "\n") if self.params.export_point_roi: pm12Sources = ArrayList() pm12Targets = ArrayList() PointMatch.sourcePoints(pm12, pm12Sources) PointMatch.targetPoints(pm12, pm12Targets) roi1 = pointsToPointRoi(pm12Sources) roi2 = pointsToPointRoi(pm12Targets) # # Adapted from BlockMatching.java # # https://github.com/axtimwalde/mpicbg/blob/master/mpicbg/src/main/java/mpicbg/ij/blockmatching/BlockMatching.java # tTarget = TranslationModel2D() # sTarget = SimilarityModel2D() # tTarget.set(-self.params.search_radius, -self.params.search_radius) # sTarget.set(1.0/self.params.scale, 0, 0, 0) # lTarget = CoordinateTransformList() # lTarget.add(sTarget) # lTarget.add(tTarget) # lTarget.add(t) # targetMapping = TransformMapping(lTarget) # mappedScaledTarget = FloatProcessor(fp1.getWidth() + 2*search_radius, fp1.getHeight() + 2*search_radius) # targetMapping.mapInverseInterpolated(fp2, mappedScaledTarget) # imp1 = tileImagePlus("imp1", fp1) # imp1.show() # imp2 = ImagePlus("imp2", mappedScaledTarget) # imp2.show() imp1 = ImagePlus("imp1", fp1) imp1.show() imp2 = ImagePlus("imp2", fp2) imp2.show() imp1.setRoi(roi1) imp2.setRoi(roi2) if self.params.export_displacement_vectors: pm12Targets = ArrayList() PointMatch.targetPoints(pm12, pm12Targets) maskSamples2 = RealPointSampleList(2) for point in pm12Targets: maskSamples2.add(RealPoint(point.getW()), ARGBType(-1)) factory = ImagePlusImgFactory() kdtreeMatches = KDTree(color_samples) kdtreeMask = KDTree(maskSamples) img = factory.create([fp1.getWidth(), fp1.getHeight()], ARGBType()) self.drawNearestNeighbor( img, NearestNeighborSearchOnKDTree(kdtreeMatches), NearestNeighborSearchOnKDTree(kdtreeMask)) scaled_img = self.scaleIntImagePlus(img, 0.03) if self.params.save_data: fs = FileSaver(scaled_img) fs.saveAsTiff(self.params.output_folder + str(self.patchB) + "_" + str(self.patchA) + ".tif") else: scaled_img.show() print time.asctime() print str(self.patchB) + "_" + str(self.patchA) + "\tsaved" IJ.log(time.asctime()) IJ.log(str(self.patchB) + "_" + str(self.patchA) + ": saved") except Exception, ex: self.exception = ex print str(ex) IJ.log(str(ex)) if self.params.save_data and self.wf: self.wf.write(str(ex) + "\n")
def import_and_straighten(imgDir): """ Core function. Opens images in given directory in series and calls a straightening function. Thresholds using weka if stddev of pixel intensities is too high (bright field), otherwise uses histogram based segmentation. """ targetWidth = 800 #adjustable make_directory(imgDir) index = "000000000" filename = imgDir + "/img_" + index + "__000.tif" if path.exists(filename): weka = Weka_segmentor(IJ.openImage(filename)) while path.exists(filename): IJ.run("Set Measurements...", "mean standard min center redirect=None decimal=3") IJ.run("Clear Results") imp = IJ.openImage(filename) imp.show() IJ.run("Rotate 90 Degrees Left") IJ.run("Measure") table = RT.getResultsTable() stddev = RT.getValue(table, "StdDev", 0) if stddev < 20: segmented = weka.getThreshold(imp) segmented.show() IJ.run("8-bit") IJ.run("Invert") imp.close() imp = segmented else: IJ.run(imp, "Auto Threshold", "method=Li white") #threshold imp = preProcess_(imp) #straighten_roi_rotation() coords = run_straighten() newImp = IJ.getImage() """ fs = FileSaver(newImp) fs.saveAsTiff(imgDir + "/straightened" + "/img_" + index + "__000-straight.tif") """ IJ.run("Image Padder", "pad_right="+str(targetWidth - newImp.getWidth())) paddedImp = IJ.getImage() fs = FileSaver(paddedImp) fs.saveAsTiff(imgDir + "/binary" + "/img_" + index + "__000-padded.tif") IJ.runMacro("while (nImages>0) {selectImage(nImages);close();}") #use same centerline for original greyscale image imp = IJ.openImage(filename) imp.show() IJ.run("Rotate 90 Degrees Left") IJ.run("8-bit") IJ.runMacro("makeLine("+coords+")") IJ.run("Straighten...", "line = 80") newImp = IJ.getImage() IJ.run("Image Padder", "pad_right="+str(targetWidth - newImp.getWidth())) paddedImp = IJ.getImage() IJ.run("8-bit") fs = FileSaver(paddedImp) fs.saveAsTiff(imgDir + "/greyscale" + "/img_" + index + "__000-padded.tif") IJ.runMacro("while (nImages>0) {selectImage(nImages);close();}") index = to_9_Digits(str(int(index)+1)) filename = filename = imgDir + "/img_" + index + "__000.tif"
def run(): ### Default arguments two_sarcomere_size = 25 # determined by filter used. rotation_angle = 0.0 ### Get the image we'd like to work with. # Don't need to ask where to save the intermediate image since it'll just be saved in the matchedmyo folder anyway # may change this though. In case they want to keep that image around. this_img = WindowManager.getCurrentImage() if this_img == None: ud = WaitForUserDialog( "Please select the image you would like to analyze.") ud.show() this_img = WindowManager.getCurrentImage() img_name = this_img.getTitle() matchedmyo_path = "/home/AD/dfco222/scratchMarx/matchedmyo/" # this would be grabbed from the prompt gd = GenericDialog("Preprocessing Options") gd.addCheckbox("Automatic Resizing/Rotation", True) gd.addCheckbox("CLAHE", True) gd.addCheckbox("Normalization to Transverse Tubules", True) gd.showDialog() if gd.wasCanceled(): return auto_resize_rotate = gd.getNextBoolean() clahe = gd.getNextBoolean() normalize = gd.getNextBoolean() if auto_resize_rotate: # Clear selection so it takes FFT of full image rotation_angle = auto_resize_angle_measure(this_img, two_sarcomere_size) if clahe: clahe_args = "blocksize={} histogram=256 maximum=3 mask=*None* fast_(less_accurate)".format( two_sarcomere_size) IJ.run(this_img, "Enhance Local Contrast (CLAHE)", clahe_args) if normalize: # Ask the user to select a subsection of the image that looks healthy-ish. ud = WaitForUserDialog( "Please select a subsection exhibiting a measure of healthy TT structure using the Rectangle tool.\n" + " Only a single cell or several are needed.\n\n" + " Press 'OK' when finished.") ud.show() IJ.setTool("rectangle") # Duplicate the selected subsection. selection = this_img.crop() IJ.run(selection, "Duplicate...", "title=subsection.tif") # Grab the subsection image and rotate it. selection = WindowManager.getImage("subsection.tif") IJ.run( selection, "Rotate...", "angle={} grid=1 interpolation=Bicubic enlarge".format( rotation_angle)) # Ask the user to select a bounding box that contains only tubules # NOTE: Need to get rid of initial selection since it's the entire image and it's annoying to click out of IJ.setTool("rectangle") IJ.run(selection, "Select None", "") ud = WaitForUserDialog( "Select a subsection of the image that contains only tubules and no membrane." ) ud.show() # Grab the subsection ImagePlus selection = WindowManager.getCurrentImage() this_window = WindowManager.getActiveWindow() selection_small = selection.crop() IJ.run(selection, "Close", "") # NOTE: May not actually display this depending on how the macros work IJ.run(selection_small, "Duplicate...", "title=subsection_small.tif") # Smooth the selection using the single TT filter. # NOTE: It won't read in so we're just going to hard code it in since it's simple tt_filt_row = "0 0 0 1 1 1 1 1 1 0 0 0 0\n" tt_filt = "" for i in range(21): tt_filt += tt_filt_row IJ.run("Convolve...", "text1=[" + tt_filt + "] normalize") # Segment out the TTs from the 'gaps' using Gaussian Adaptive Thresholding. selection_small = WindowManager.getImage("subsection_small.tif") IJ.run(selection_small, "Duplicate...", "title=thresholded.tif") threshed = WindowManager.getImage("thresholded.tif") IJ.run(threshed, "Auto Local Threshold", "method=Bernsen radius=7 parameter_1=1 parameter_2=0 white") # Select the TTs from the thresholded image. IJ.run(threshed, "Create Selection", "") tt_selection = WindowManager.getImage("subsection_small.tif") IJ.selectWindow("thresholded.tif") IJ.selectWindow("subsection_small.tif") IJ.run(tt_selection, "Restore Selection", "") # Get TT intensity statistics. stat_options = IS.MEAN | IS.MIN_MAX | IS.STD_DEV stats = IS.getStatistics(tt_selection.getProcessor(), stat_options, selection_small.getCalibration()) # Calculate pixel ceiling intensity value based on heuristic. # TODO: Add a catch for data type overflow. pixel_ceiling = stats.mean + 3 * stats.stdDev print "px ceil:", pixel_ceiling # Invert selection to get inter-sarcomeric gap intensity statistics. IJ.run(tt_selection, "Make Inverse", "") stat_options = IS.MEAN | IS.MIN_MAX | IS.STD_DEV stats = IS.getStatistics(tt_selection.getProcessor(), stat_options, selection_small.getCalibration()) # Calculate pixel floor intensity value based on heuristic. pixel_floor = stats.mean - stats.stdDev # TODO: Add a catch for data type underflow. print "px floor:", pixel_floor # Threshold original image based on these values. IJ.selectWindow(this_img.getTitle()) IJ.run(this_img, "Select All", "") IJ.setMinAndMax(pixel_floor, pixel_ceiling) IJ.run(this_img, "Apply LUT", "") ## Ask if it is acceptable. gd = GenericDialog("Acceptable?") gd.addMessage( "If the preprocessed image is acceptable for analysis, hit 'OK' to being analysis.\n" + " If the image is unacceptable or an error occurred, hit 'Cancel'") gd.showDialog() if gd.wasCanceled(): return ## Save the preprocessed image. imp = IJ.getImage() fs = FileSaver(imp) img_save_dir = matchedmyo_path + "myoimages/" # actually get from user at some point img_file_path = img_save_dir + img_name[:-4] + "_preprocessed.tif" if os.path.exists(img_save_dir) and os.path.isdir(img_save_dir): print "Saving image as:", img_file_path if os.path.exists(img_file_path): # use dialog box to ask if they want to overwrite gd = GenericDialog("Overwrite?") gd.addMessage( "A file exists with the specified path, \"{}\". Would you like to overwrite it?" .format(img_file_path)) gd.enableYesNoCancel() gd.showDialog() if gd.wasCanceled(): return elif fs.saveAsTiff(img_file_path): print "Preprocessed image saved successfully at:", '"' + img_file_path + '"' else: print "Folder does not exist or is not a folder!" ### Create the YAML file containing the parameters for classification ## Ask user for YAML input gd = GenericDialog("YAML Input") gd.addStringField("imageName", img_file_path, 50) #gd.addStringField("maskName", "None") gd.addStringField("outputParams_fileRoot", img_file_path[:-4], 50) gd.addStringField("outputParams_fileType", "tif") gd.addNumericField("outputParams_dpi", 300, 0) gd.addCheckbox("outputParams_saveHitsArray", False) gd.addStringField("outputParams_csvFile", matchedmyo_path + "results/") gd.addCheckbox("TT Filtering", True) gd.addToSameRow() gd.addCheckbox("LT Filtering", True) gd.addToSameRow() gd.addCheckbox("TA Filtering", True) gd.addNumericField("scopeResolutions_x", 5.0, 3) gd.addToSameRow() gd.addNumericField("scopeResolutions_y", 5.0, 3) gd.addMessage("Enter in filter rotation angles separated by commas.") gd.addStringField("", "-25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25", 50) gd.addCheckbox("returnAngles", False) gd.addCheckbox("returnPastedFilter", True) gd.showDialog() if gd.wasCanceled(): return strings = [st.text for st in gd.getStringFields()] #if strings[1] == "None" or "": # strings[1] = None nums = [float(num.text) for num in gd.getNumericFields()] nums[0] = int(nums[0]) # Have to make sure the dpi variable is an integer checks = [str(bool(boo.state)) for boo in gd.getCheckboxes()] iter_argument = ','.join( [str(float(it) - rotation_angle) for it in strings[4].split(',')]) string_block = """imageName: {0[0]} outputParams: fileRoot: {0[1]} fileType: {0[2]} dpi: {1[0]} saveHitsArray: {2[0]} csvFile: {0[3]} preprocess: False filterTypes: TT: {2[1]} LT: {2[2]} TA: {2[3]} scopeResolutions: x: {1[1]} y: {1[2]} iters: [{3}] returnAngles: {2[4]} returnPastedFilter: {2[5]}""".format(strings, nums, checks, iter_argument) im_title = this_img.getTitle() with cd(matchedmyo_path): yaml_file_path = "./YAML_files/" + im_title[:-4] + ".yml" with open("./YAML_files/" + im_title[:-4] + ".yml", "w") as ym: ym.write(string_block) print "Wrote YAML file to:", matchedmyo_path + yaml_file_path[2:] ### Run the matchedmyo code on the preprocessed image with cd(matchedmyo_path): #os.chdir(matchedmyo_path) #subprocess.call(["python3", matchedmyo_path+"matchedmyo.py", "fullValidation"]) subprocess.call( ["python3", "matchedmyo.py", "run", "--yamlFile", yaml_file_path])
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()
tifName = fName + ".tif" tifPath = os.path.join(fPath, tifName) print(fName) imp.changes = False wid = imp.getWidth() mu = IJ.micronSymbol scaUni = mu + "m" argThree = "distance=%g known=%f pixel=1 unit=%s" % (wid, fwMicrons, scaUni) IJ.run(imp, "Set Scale...", argThree) IJ.run(imp, "Enhance Contrast", "saturated=0.35") fs = FileSaver(imp) 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) imp.setTitle(fName) fs = FileSaver(imp) pngName = fName + ".png"