def setReaderOptions(imagefile, stitchtiles=False, setflatres=True, setconcat=False, openallseries=False, showomexml=False, attach=False, autoscale=True): czi_options = DynamicMetadataOptions() czi_options.setBoolean("zeissczi.autostitch", stitchtiles) czi_options.setBoolean("zeissczi.attachments", attach) # set the option for the CZIReader czireader = ImportTools.setCZIReaderOptions(imagefile, czi_options, setflatres=setflatres) # Set the preferences in the ImageJ plugin # Note although these preferences are applied, they are not refreshed in the UI Prefs.set("bioformats.zeissczi.allow.autostitch", str(stitchtiles).lower()) Prefs.set("bioformats.zeissczi.include.attachments", str(attach).lower()) # set the option for the BioFormats import reader_options = ImporterOptions() reader_options.setOpenAllSeries(openallseries) reader_options.setShowOMEXML(showomexml) reader_options.setConcatenate(setconcat) reader_options.setAutoscale(autoscale) reader_options.setStitchTiles(stitchtiles) reader_options.setId(imagefile) return reader_options, czireader
def showDialogR(R, val): """ Create dialog for input and save R values in settings """ gui = GenericDialog("Heterogeneous Z Correction") msg = "Heterogeneous Z Correction calculates an optical model\n"\ "based on rational fluorescence intensity attenuation\n"\ "over depth, in the form of (ax+b)/(x+c). Please specify\n"\ "(a,b,c) for each region. You should provide a z-stack with\n"\ "unique pixel values for each region.\n" gui.addMessage(msg) for ii in range(len(val)): gui.addNumericField( "Region " + str(ii) + " (" + str(val[ii]) + "): a", R[ii][0], 2) gui.addToSameRow() gui.addNumericField("b", R[ii][1], 2) gui.addToSameRow() gui.addNumericField("c", R[ii][2], 2) gui.addHelp( r"https://github.com/alexandrebastien/heterogeneous-z-correction") gui.showDialog() if gui.wasOKed(): R = [] for ii in range(len(val)): R = R + [ (gui.getNextNumber(), gui.getNextNumber(), gui.getNextNumber()) ] Prefs.set("HetZCorr.R", str(R)) return R else: return
def actionPerformed(self, event): """Delete the last row""" # Generate a save dialog dialog = JFileChooser(Prefs.get("roiGroup.importDir", "")) dialog.setSelectedFile(File("roiGroups.txt")) dialog.setFileFilter(FileNameExtensionFilter("Text file", ["txt"])) output = dialog.showOpenDialog( self.groupTable) # could be None argument too if output in [JFileChooser.CANCEL_OPTION, JFileChooser.ERROR_OPTION]: return selectedFile = dialog.getSelectedFile() directory = selectedFile.getParent() Prefs.set("roiGroup.importDir", directory) if not selectedFile.isFile(): return filePath = selectedFile.getPath() # Read comma-separated group from file with open(filePath, "r") as textFile: stringGroup = textFile.readline().rstrip() # Update table with content of file tableModel = self.groupTable.tableModel tableModel.setGroupColumn(stringGroup)
def getListCategories(self): """ Read the new category names entered by user in the GUI. Save the values as a comma-separated string in persistence. """ listCategories = [] for textField in self.panel.getComponents(): newCategory = textField.getText() if newCategory: listCategories.append(newCategory) Prefs.set("annot.listCat", ",".join(listCategories) ) # save the new list of categories return listCategories
def makeCategoryComponent(self, category): """ Generates a checkbox with the new category name, to add to the GUI Overwrite the original method """ stringCat = Prefs.get("annot.listCat", "") newStringCat = stringCat + "," + category if stringCat else category Prefs.set("annot.listCat", newStringCat) # Make a new checkbox with the category name checkbox = Checkbox(category, False) checkbox.setFocusable( False) # important to have the keybard shortcut working return checkbox
self.defaultActionSequence() def makeCategoryComponent(self, category): """Return a button with the new category name, and mapped to the action""" listCat.append(category) # Save the new category in memory Prefs.set("annot.listCat", ",".join(listCat) ) button = JButton(category) button.addActionListener(categoryAction) button.setFocusable(False) # Add button tooltip if fit in the F1-F12 button range nCat = len(listCat) if nCat <= 12: button.setToolTipText("Keyboard shortcut: F" + str(nCat)) # F shortcut labels are 1-based, ie match the len value
def actionPerformed(self, event): ''' Handle buttons clicks, delegates to custom methods OK: save parameters in memory Add new category: delegate to addCategoryComponent() (should be overwritten in daughter) Add: delegate to addAction() NB: NEVER use getNext methods here, since we call them several time ''' source = event.getSource() # test here if it is a button if isinstance( source, Button ): # if type is a button get label, and check command, otherwise pass to GenericDialogPlus.actionPeformed sourceLabel = source.getLabel() if sourceLabel == CustomDialog.LABEL_OK: # Check options and save them in persistence checkboxes = self.getCheckboxes() doNext = checkboxes[-1].getState() Prefs.set("annot.doNext", doNext) # Save selected dimension if mode stack if self.browseMode == "stack": Prefs.set("annot.dimension", self.getSelectedDimension()) elif sourceLabel == "Add new category": self.addCategoryComponent() elif sourceLabel == self.LABEL_ADD: self.addAction() else: pass # Anyway do the mother class usual action handling GenericDialogPlus.actionPerformed(self, event)
def actionPerformed(self, event): """Delete the last row""" # Generate a save dialog dialog = JFileChooser(Prefs.get("roiGroup.exportDir", "")) dialog.setSelectedFile(File("roiGroups.txt")) dialog.setFileFilter(FileNameExtensionFilter("Text file", ["txt"])) output = dialog.showSaveDialog( self.groupTable) # could be argument None too if output in [JFileChooser.CANCEL_OPTION, JFileChooser.ERROR_OPTION]: return selectedFile = dialog.getSelectedFile() directory = selectedFile.getParent() Prefs.set("roiGroup.exportDir", directory) filePath = selectedFile.getPath() if not ("." in filePath): filePath += ".txt" # Add extension if missing # Write the groupString to the file groupString = self.groupTable.tableModel.getGroupString() with open(filePath, "w") as textFile: textFile.write(groupString)
def readczi(imagefile, stitchtiles=True, setflatres=False, readpylevel=0, setconcat=True, openallseries=True, showomexml=False, attach=False, autoscale=True): log.info('Filename : ' + imagefile) metainfo = {} # checking for thr file Extension metainfo['Extension'] = MiscTools.getextension(MiscTools.splitext_recurse(imagefile)) log.info('Detected File Extension : ' + metainfo['Extension']) # initialize the reader and get the OME metadata reader = ImageReader() omeMeta = MetadataTools.createOMEXMLMetadata() #metainfo['ImageCount_OME'] = omeMeta.getImageCount() reader.setMetadataStore(omeMeta) reader.setId(imagefile) metainfo['SeriesCount_BF'] = reader.getSeriesCount() reader.close() # get the scaling for XYZ physSizeX = omeMeta.getPixelsPhysicalSizeX(0) physSizeY = omeMeta.getPixelsPhysicalSizeY(0) physSizeZ = omeMeta.getPixelsPhysicalSizeZ(0) if physSizeX is not None: metainfo['ScaleX'] = round(physSizeX.value(), 3) metainfo['ScaleY'] = round(physSizeX.value(), 3) if physSizeX is None: metainfo['ScaleX'] = None metainfo['ScaleY'] = None if physSizeZ is not None: metainfo['ScaleZ'] = round(physSizeZ.value(), 3) if physSizeZ is None: metainfo['ScaleZ'] = None options = DynamicMetadataOptions() options.setBoolean("zeissczi.autostitch", stitchtiles) options.setBoolean("zeissczi.attachments", attach) czireader = ZeissCZIReader() czireader.setFlattenedResolutions(setflatres) czireader.setMetadataOptions(options) czireader.setId(imagefile) # Set the preferences in the ImageJ plugin # Note although these preferences are applied, they are not refreshed in the UI Prefs.set("bioformats.zeissczi.allow.autostitch", str(stitchtiles).lower()) Prefs.set("bioformats.zeissczi.include.attachments", str(attach).lower()) # metainfo = {} metainfo['rescount'] = czireader.getResolutionCount() metainfo['SeriesCount_CZI'] = czireader.getSeriesCount() #metainfo['flatres'] = czireader.hasFlattenedResolutions() #metainfo['getreslevel'] = czireader.getResolution() # Dimensions metainfo['SizeT'] = czireader.getSizeT() metainfo['SizeZ'] = czireader.getSizeZ() metainfo['SizeC'] = czireader.getSizeC() metainfo['SizeX'] = czireader.getSizeX() metainfo['SizeY'] = czireader.getSizeY() # check for autostitching and possibility to read attachment metainfo['AllowAutoStitching'] = czireader.allowAutostitching() metainfo['CanReadAttachments'] = czireader.canReadAttachments() # read in and display ImagePlus(es) with arguments options = ImporterOptions() options.setOpenAllSeries(openallseries) options.setShowOMEXML(showomexml) options.setConcatenate(setconcat) options.setAutoscale(autoscale) options.setId(imagefile) # open the ImgPlus imps = BF.openImagePlus(options) metainfo['Pyramid Level Output'] = readpylevel + 1 try: imp = imps[readpylevel] pylevelout = metainfo['SeriesCount_CZI'] except: # fallback option log.info('PyLevel=' + str(readpylevel) + ' does not exist.') log.info('Using Pyramid Level = 0 as fallback.') imp = imps[0] pylevelout = 0 metainfo['Pyramid Level Output'] = pylevelout # get the stack and some info imgstack = imp.getImageStack() metainfo['Output Slices'] = imgstack.getSize() metainfo['Output SizeX'] = imgstack.getWidth() metainfo['Output SizeY'] = imgstack.getHeight() # calc scaling in case of pyramid scale = float(metainfo['SizeX']) / float(metainfo['Output SizeX']) metainfo['Pyramid Scale Factor'] = scale metainfo['ScaleX Output'] = metainfo['ScaleX'] * scale metainfo['ScaleY Output'] = metainfo['ScaleY'] * scale # set the correct scaling imp = MiscTools.setscale(imp, scaleX=metainfo['ScaleX Output'], scaleY=metainfo['ScaleX Output'], scaleZ=metainfo['ScaleZ'], unit="micron") # close czireader czireader.close() return imp, metainfo
class Colortags: ''' This class handles persistence of the name of different color channels. It instantiates a GUI window to capture and show the color names in use. Other classes such as ColorMerger needs this to determine the color of the channel being processed. ''' def __init__(self): self.window = None self.tags = {} self.prefkeys = ["{0}.{1}".format(SUBKEY, name) for name in COLORS] self.userprefs = Prefs() self.load() while not self.tags: self.edit("Please set at least one colortag.\n\n") def load(self): ''' Tries to load IBPlib colortags from IJ prefs. ''' for i in range(7): storedtags = self.userprefs.getString(".{0}".format(self.prefkeys[i]), "") if not storedtags: continue trimmedtagslist = [t.strip() for t in storedtags.split(",")] self.tags.update({i:trimmedtagslist}) def edit(self, msg=""): ''' Opens the color tags dialog to update color tags ''' self.window = GenericDialog("ColorMerger - Edit color tags") self.window.addMessage("{0}Separate tags with a comma.\nBlank values will be ignored.".format(msg)) for i in range(7): try: self.window.addStringField(COLORS[i], ", ".join(self.tags[i]), 30) except KeyError: self.window.addStringField(COLORS[i], "", 30) self.window.setOKLabel("Save") self.window.showDialog() if self.window.wasOKed(): self.__savetags() self.load() def __validate(self): fields = self.window.getStringFields() newvalues = {} for i in range(len(fields)): txt = fields[i].getText() newvalues.update({i: txt.strip()}) return newvalues def __savetags(self): newvalues = self.__validate() for i, tags in newvalues.items(): key = self.prefkeys[i] self.userprefs.set(key, tags) self.userprefs.savePreferences()
def readCZI(imagefile, metainfo, stitchtiles=False, setflatres=False, readpylevel=0, setconcat=False, openallseries=True, showomexml=False, attach=False, autoscale=True): options = DynamicMetadataOptions() options.setBoolean("zeissczi.autostitch", stitchtiles) options.setBoolean("zeissczi.attachments", attach) czireader = ZeissCZIReader() czireader.setFlattenedResolutions(setflatres) czireader.setMetadataOptions(options) czireader.setId(imagefile) # Set the preferences in the ImageJ plugin # Note although these preferences are applied, they are not refreshed in the UI Prefs.set("bioformats.zeissczi.allow.autostitch", str(stitchtiles).lower()) Prefs.set("bioformats.zeissczi.include.attachments", str(attach).lower()) # metainfo = {} metainfo['rescount'] = czireader.getResolutionCount() metainfo['SeriesCount_CZI'] = czireader.getSeriesCount() metainfo['flatres'] = czireader.hasFlattenedResolutions() # metainfo['getreslevel'] = czireader.getResolution() # Dimensions metainfo['SizeT'] = czireader.getSizeT() metainfo['SizeZ'] = czireader.getSizeZ() metainfo['SizeC'] = czireader.getSizeC() metainfo['SizeX'] = czireader.getSizeX() metainfo['SizeY'] = czireader.getSizeY() # check for autostitching and possibility to read attachment metainfo['AllowAutoStitching'] = czireader.allowAutostitching() metainfo['CanReadAttachments'] = czireader.canReadAttachments() # read in and display ImagePlus(es) with arguments options = ImporterOptions() options.setOpenAllSeries(openallseries) options.setShowOMEXML(showomexml) options.setConcatenate(setconcat) options.setAutoscale(autoscale) options.setId(imagefile) # open the ImgPlus imps = BF.openImagePlus(options) metainfo['Pyramid Level Output'] = readpylevel # read image data using the specified pyramid level imp, slices, width, height, pylevel = ImageTools.getImageSeries(imps, series=readpylevel) metainfo['Pyramid Level Output'] = pylevel metainfo['Output Slices'] = slices metainfo['Output SizeX'] = width metainfo['Output SizeY'] = height # calc scaling in case of pyramid # scale = float(metainfo['Output SizeX']) / float(metainfo['SizeX']) scale = float(metainfo['SizeX']) / float(metainfo['Output SizeX']) metainfo['Pyramid Scale Factor'] = scale metainfo['ScaleX Output'] = metainfo['ScaleX'] * scale metainfo['ScaleY Output'] = metainfo['ScaleY'] * scale """ imp = MiscTools.setproperties(imp, scaleX=metainfo['ScaleX Output'], scaleY=metainfo['ScaleX Output'], scaleZ=metainfo['ScaleZ'], unit="micron", sizeC=metainfo['SizeC'], sizeZ=metainfo['SizeZ'], sizeT=metainfo['SizeT']) """ imp = MiscTools.setscale(imp, scaleX=metainfo['ScaleX Output'], scaleY=metainfo['ScaleX Output'], scaleZ=metainfo['ScaleZ'], unit="micron") # close czireader czireader.close() return imp, metainfo
def setLastMeasureCount(count): count = int(count) Prefs.set("JRM.meas.counter", count)
def resetLastMeasureCount(): Prefs.set("JRM.meas.counter", 0)
bDoTiltCorrect = False mu = IJ.micronSymbol scaUm = mu + "m" lastPath = Prefs.get("Last.Image.Dir", "None") if os.path.exists(lastPath): os.chdir(lastPath) dc = DirectoryChooser("Choose directory") basePath = dc.getDirectory() print(basePath) Prefs.set("Last.Image.Dir", basePath) names = [] for file in os.listdir(basePath): if file.endswith(".tif"): name = os.path.splitext(file)[0] names.append(name) names.sort() for name in names: path = basePath + os.sep + name + ".tif" if bVerbose: print(path) sPngPath = basePath + "/png/"
def getCZIinfo(imagefile, showimage=False, setreslevel=0, setflat2=False, openallseries=True, showomexml=False,setconcat=False,filepath1="./"): options = DynamicMetadataOptions() options.setBoolean("zeissczi.attachments", False) czireader = ZeissCZIReader() czireader.setFlattenedResolutions(setflat2) czireader.setMetadataOptions(options) czireader.setId(imagefile) lc = czireader.getSeriesCount() #get the first occurence of each pyramid stack location=list() for i in range(0, int(seriesCount)-2): location.append(czireader.coreIndexToSeries(i)) c=0 #log.info(location) loc2=list() for i,v in enumerate(location): if i==0: loc2.append(i) elif i>0 and v!=c: loc2.append(i) c=v log.info(str(loc2)) # get OME data omeMeta = MetadataTools.createOMEXMLMetadata() # Set the preferences in the ImageJ plugin Prefs.set("bioformats.zeissczi.include.attachments", str(True).lower()) if showimage: # read in and display ImagePlus(es) with arguments options = ImporterOptions() options.setOpenAllSeries(openallseries) options.setShowOMEXML(showomexml) options.setConcatenate(setconcat) options.setId(imagefile) # open the ImgPlus imps = BF.openImagePlus(options) name_list=imagefile.split('/') name=name_list[len(name_list)-1] out_path=filepath1 + "/"+name+"_Preview.tif" log.info(name) imp=getImageSeries(imps, seriesCount-1) imp.show() IJ.run("RGB Color") imp.close() IJ.saveAs("tiff", out_path) IJ.run("Close") out_path=filepath1 + "/"+name+"_Label.tif" imp=getImageSeries(imps, (seriesCount-2)) imp.show() IJ.run("RGB Color") imp.close() IJ.saveAs("tiff", out_path) IJ.run("Close") c=1 for series in loc2: out_path=filepath1 + "/"+name+"Scene_" + str(c) + ".tif" imp=getImageSeries(imps, series) imp.show() IJ.run("RGB Color") imp.close() IJ.saveAs("tiff", out_path) IJ.run("Close") c+=1 czireader.close()
def main(): Interpreter.batchMode = True if (lambda_flat == 0) ^ (lambda_dark == 0): print ("ERROR: Both of lambda_flat and lambda_dark must be zero," " or both non-zero.") return lambda_estimate = "Automatic" if lambda_flat == 0 else "Manual" print "Loading images..." # For multi-scene .CZI files, we need raw tiles instead of the # auto-stitched mosaic and we don't want labels or overview images. This # only affects BF.openImagePlus, not direct use of the BioFormats reader # classes which we also do (see below) Prefs.set("bioformats.zeissczi.allow.autostitch", "false") Prefs.set("bioformats.zeissczi.include.attachments", "false") # Use BioFormats reader directly to determine dataset dimensions without # reading every single image. The series count (num_images) is the one value # we can't easily get any other way, but we might as well grab the others # while we have the reader available. dyn_options = DynamicMetadataOptions() # Directly calling a BioFormats reader will not use the IJ Prefs settings # so we need to pass these options explicitly. dyn_options.setBoolean("zeissczi.autostitch", False) dyn_options.setBoolean("zeissczi.attachments", False) bfreader = ImageReader() bfreader.setMetadataOptions(dyn_options) bfreader.id = str(filename) num_images = bfreader.seriesCount num_channels = bfreader.sizeC width = bfreader.sizeX height = bfreader.sizeY bfreader.close() # The internal initialization of the BaSiC code fails when we invoke it via # scripting, unless we explicitly set a the private 'noOfSlices' field. # Since it's private, we need to use Java reflection to access it. Basic_noOfSlices = Basic.getDeclaredField('noOfSlices') Basic_noOfSlices.setAccessible(True) basic = Basic() Basic_noOfSlices.setInt(basic, num_images) # Pre-allocate the output profile images, since we have all the dimensions. ff_image = IJ.createImage("Flat-field", width, height, num_channels, 32); df_image = IJ.createImage("Dark-field", width, height, num_channels, 32); print("\n\n") # BaSiC works on one channel at a time, so we only read the images from one # channel at a time to limit memory usage. for channel in range(num_channels): print "Processing channel %d/%d..." % (channel + 1, num_channels) print "===========================" options = ImporterOptions() options.id = str(filename) options.setOpenAllSeries(True) # concatenate=True gives us a single stack rather than a list of # separate images. options.setConcatenate(True) # Limit the reader to the channel we're currently working on. This loop # is mainly why we need to know num_images before opening anything. for i in range(num_images): options.setCBegin(i, channel) options.setCEnd(i, channel) # openImagePlus returns a list of images, but we expect just one (a # stack). input_image = BF.openImagePlus(options)[0] # BaSiC seems to require the input image is actually the ImageJ # "current" image, otherwise it prints an error and aborts. WindowManager.setTempCurrentImage(input_image) basic.exec( input_image, None, None, "Estimate shading profiles", "Estimate both flat-field and dark-field", lambda_estimate, lambda_flat, lambda_dark, "Ignore", "Compute shading only" ) input_image.close() # Copy the pixels from the BaSiC-generated profile images to the # corresponding channel of our output images. ff_channel = WindowManager.getImage("Flat-field:%s" % input_image.title) ff_image.slice = channel + 1 ff_image.getProcessor().insert(ff_channel.getProcessor(), 0, 0) ff_channel.close() df_channel = WindowManager.getImage("Dark-field:%s" % input_image.title) df_image.slice = channel + 1 df_image.getProcessor().insert(df_channel.getProcessor(), 0, 0) df_channel.close() print("\n\n") template = '%s/%s-%%s.tif' % (output_dir, experiment_name) ff_filename = template % 'ffp' IJ.saveAsTiff(ff_image, ff_filename) ff_image.close() df_filename = template % 'dfp' IJ.saveAsTiff(df_image, df_filename) df_image.close() print "Done!"