def getOK(text): gd = GenericDialog('User prompt') gd.addMessage(text) gd.hideCancelButton() gd.enableYesNoCancel() gd.showDialog() return gd.wasOKed()
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 _dialog(self,comment): gd = GenericDialog(comment) gd.enableYesNoCancel() gd.showDialog() if gd.wasCanceled(): print "user cancelled dialog" sys.exit(1) option = gd.wasOKed() return option
def get_metadata_table_filepath(): """Get a the metadata template filename""" d = GenericDialog("Metadata Template") d.addMessage("Please choose a metadata template") d.enableYesNoCancel("OK", "Cancel") d.hideCancelButton() d.showDialog() if d.wasOKed(): od = OpenDialog("Metadata File") return os.path.join(od.getDirectory(), od.getFileName()) else: return
def perform_manual_qc(imp, rois, important_channel=1): """given cell rois generated by automatic methods, allow user to delete/add/redraw as appropriate""" for ch in range(imp.getNChannels()): imp.setC(ch + 1) sat_frac = 0.99 if (ch + 1) == important_channel else 0.01 IJ.run(imp, "Enhance Contrast", "saturated={}".format(sat_frac)) imp.setC(important_channel) IJ.setTool("freehand") proceed = False roim = RoiManager() roim.runCommand("Show all with labels") for roi in rois: roim.addRoi(roi) auto_rois_only = rois while not proceed: dialog = NonBlockingGenericDialog("Perform manual segmentation") dialog.setOKLabel("Proceed to next image...") dialog.addMessage("Perform manual correction of segmentation: ") dialog.addMessage( "Draw around cells and add to the region of interest manager (Ctrl+T). " ) dialog.addMessage("Delete and redraw cells as appropriate. ") dialog.addMessage( "Then press \"proceed to next image\" when all cells have been added. " ) dialog.showDialog() if dialog.wasCanceled(): print("Manual segmentation canceled") return auto_rois_only elif dialog.wasOKed(): if roim.getCount() == 0: rois = [] confirm_dialog = GenericDialog("Continue?") confirm_dialog.addMessage( "No rois selected in this FOV. Are you sure you want to proceed?" ) confirm_dialog.setOKLabel("Yes, proceed") confirm_dialog.setCancelLabel("No, not yet") confirm_dialog.showDialog() if confirm_dialog.wasOKed(): proceed = True else: rois = roim.getRoisAsArray() proceed = True roim.reset() roim.close() for ch in range(imp.getNChannels()): imp.setC(ch + 1) IJ.run(imp, "Enhance Contrast", "saturated={}".format(0.35)) imp.setC(important_channel) return rois
def save_etc(imp, info, output_folder): """handle saving output, final labelling and UI of what to do next""" dialog = GenericDialog("Marksl1 cell shape prescreen"); dialog.addChoice("Vessel type: ", info.get_vessel_types(), info.get_vessel_type()); dialog.addStringField("Channel 1 label: ", info.get_ch1_label()); dialog.addStringField("Channel 2 label: ", info.get_ch2_label()); dialog.addStringField("Experiment identifier: ", info.get_experiment_id()); dialog.addStringField("Embryo identifier: ", info.get_embryo_id()); dialog.setOKLabel("Save preprocessing"); dialog.showDialog(); info.set_vessel_type(dialog.getNextChoice()); info.set_ch1_label(dialog.getNextString()); info.set_ch2_label(dialog.getNextString()); info.set_experiment_id(dialog.getNextString()); info.set_embryo_id(dialog.getNextString()); if dialog.wasCanceled(): return "stop"; if dialog.wasOKed(): exsting_files = os.listdir(output_folder); r = re.compile(".*" + info.get_embryo_id() + " " + info.get_vessel_type() + ".*") fns = filter(r.match, exsting_files) numbers = list((int(s) for fn in fns for s in re.findall(r'\b\d+$', os.path.splitext(fn)[0]))); append_digit = (max(numbers) + 1) if numbers else 1; ch1str = (info.get_ch1_label() + " ") if info.get_ch1_label() else ""; ch2str = (info.get_ch2_label() + " ") if info.get_ch2_label() else ""; expstr = (info.get_experiment_id() + " ") if info.get_experiment_id() else ""; file_name = ("Cropped " + ch1str + ch2str + expstr + "e" + str(info.get_embryo_id()) + " " + info.get_vessel_type() + " " + str(append_digit)); FileSaver(imp).saveAsTiff(os.path.join(output_folder, (file_name + ".tif"))); info.save_info_to_json(os.path.join(output_folder, (file_name + ".json"))); continueDialog = YesNoCancelDialog(WM.getCurrentWindow(), "Continue?", "Continue with same input image or a new input image?", "New image...", "Same image"); if continueDialog.cancelPressed(): return "stop"; if continueDialog.yesPressed(): return "continue_newimage"; return "continue_sameimage"; return "stop";
def showTable(self): """ Add the main panel to a GenericDialog and show it """ gd = GenericDialog("Roi-group table") gd.addPanel(self) # Add current table instance to panel gd.addMessage("""If you use this plugin, please cite: Laurent Thomas. (2020, November 18). LauLauThom/RoiGroupTable: ImageJ/Fiji RoiGroup Table (Version 1.0) Zenodo. http://doi.org/10.5281/zenodo.4279049""") gd.addHelp(r"https://github.com/LauLauThom/RoiGroupTable") gd.showDialog() if gd.wasOKed(): # Update ImageJ Roi group names mapping stringGroup = self.tableModel.getGroupString() Roi.setGroupNames(stringGroup)
def inputScale(self): gd=GenericDialog("Scale ROI") gd.addStringField("X Scale:",str(self.xScale)) gd.addStringField("Y Scale:",str(self.yScale)) gd.addStringField("Scale X to pixel:",str(self.impXpixel)) gd.addStringField("Scale Y to pixel:",str(self.impYpixel)) fields=gd.getStringFields() self.XscaleField,self.YscaleField=fields[0],fields[1] self.toXfield,self.toYfield=fields[2],fields[3] self.XscaleField.addTextListener(self) self.YscaleField.addTextListener(self) self.toXfield.addTextListener(self) self.toYfield.addTextListener(self) gd.showDialog() if gd.wasOKed(): return(self.xScale,self.yScale) else: return(1.0,1.0)
def choose_series(filepath, params): """if input file contains more than one image series (xy position), prompt user to choose which one to use""" # todo: if necessary (e.g. if lots of series), can improve thumbnail visuals based loosely on https://github.com/ome/bio-formats-imagej/blob/master/src/main/java/loci/plugins/in/SeriesDialog.java import_opts = ImporterOptions(); import_opts.setId(filepath); reader = ImageReader(); ome_meta = MetadataTools.createOMEXMLMetadata(); reader.setMetadataStore(ome_meta); reader.setId(filepath); no_series = reader.getSeriesCount(); if no_series == 1: return import_opts, params; else: series_names = [ome_meta.getImageName(idx) for idx in range(no_series)]; dialog = GenericDialog("Select series to load..."); dialog.addMessage("There are multiple series in this file! \n" + "This is probably because there are multiple XY stage positions. \n " + "Please choose which series to load: "); thumbreader = BufferedImageReader(reader); cbg = CheckboxGroup(); for idx in range(no_series): p = Panel(); p.add(Box.createRigidArea(Dimension(thumbreader.getThumbSizeX(), thumbreader.getThumbSizeY()))); ThumbLoader.loadThumb(thumbreader, idx, p, True); dialog.addPanel(p); cb = Checkbox(series_names[idx], cbg, idx==0); p.add(cb); dialog.showDialog(); if dialog.wasCanceled(): raise KeyboardInterrupt("Run canceled"); if dialog.wasOKed(): selected_item = cbg.getSelectedCheckbox().getLabel(); selected_index = series_names.index(selected_item); params.setSelectedSeriesIndex(selected_index); for idx in range(0, no_series): import_opts.setSeriesOn(idx, True) if (idx==selected_index) else import_opts.setSeriesOn(idx, False); reader.close(); return import_opts, params
def get_config_file(folder): '''Returns the config file name.''' # Get list of files in the selected directory. files = os.listdir(folder) # Check if a config file is present in folder. if default_config in files: dialog = GenericDialog('Default config file found!') dialog.addMessage('Use this file for the analysis?\n \n%s' % os.path.join(folder, default_config)) dialog.enableYesNoCancel() dialog.showDialog() if dialog.wasCanceled(): return None elif dialog.wasOKed(): return default_config else: open_dialog = OpenDialog('Select a config file', folder, default_config) return open_dialog.getFileName() else: # Ask user to select a config file. open_dialog = OpenDialog('Select a config file', folder, default_config) return open_dialog.getFileName()
sizeGD.addNumericField("Tile overlap percentage",10,0) sizeGD.addCheckbox("Write fused image sequence to disk",False) sizeGD.showDialog() doComputeOverlap = sizeGD.getNextBoolean() overlapPctStr = str(sizeGD.getNextNumber()) doWriteToDisk = sizeGD.getNextBoolean() if (doComputeOverlap): overlapText = "compute_overlap ignore_z_stage" else: overlapText = "" if (doWriteToDisk): outputPath = imgDir + "substitched" diskWriteText = "image_output=[Write to disk] output_directory=[" + outputPath + "]" else: diskWriteText = "image_output=[Fuse and display]" if (sizeGD.wasOKed()): for t in tiles: shutil.copyfile(imgDir+"tile_"+str(t)+".ome.tif",imgDir+"temp/tile_"+str(ind)+".ome.tif") ind = ind + 1 IJ.showStatus("Beginning stitch...") params = ("type=[Grid: row-by-row] order=[Right & Down ] grid_size_x=" + str(xs[2]) + " grid_size_y=" + str(ys[2]) + " tile_overlap=" + overlapPctStr + " first_file_index_i=1 directory=[" + imgDir + "temp] file_names=tile_{i}.ome.tif output_textfile_name=TileConfiguration.txt " + "fusion_method=[Linear Blending] regression_threshold=0.30 max/avg_displacement_threshold=2.50 " + "absolute_displacement_threshold=3.50 " + overlapText + " subpixel_accuracy " + "computation_parameters=[Save memory (but be slower)] " + diskWriteText) IJ.run("Grid/Collection stitching", params) gd = NonBlockingGenericDialog("Explore full resolution...") gd.addMessage("Select ROI for visualization at full resolution") gd.showDialog()
def main(): metadatas = [] runagain = True offsetx = 0 offsety = 0 interval = 50.0 IJ.run(imp, "RGB Color", "") IJ.run("Colors...", "foreground=cyan background=white selection=yellow") while runagain: dialog = GenericDialog("Define 5x ROI parameters...") dialog.enableYesNoCancel("Continue and quit", "Continue and add another line") dialog.addNumericField("Line scan position 1 X, Y: ", 0, 0) dialog.addToSameRow() dialog.addNumericField(", ", 0, 0) dialog.addNumericField("Line scan position 2 X, Y: ", 0, 0) dialog.addToSameRow() dialog.addNumericField(", ", 0, 0) dialog.addNumericField("Reference image crop origin X, Y: ", offsetx, 0) dialog.addToSameRow() dialog.addNumericField(", ", offsety, 0) dialog.addNumericField("Frame interval (s): ", interval, 2) dialog.showDialog() p1x = dialog.getNextNumber() p1y = dialog.getNextNumber() p2x = dialog.getNextNumber() p2y = dialog.getNextNumber() offsetx = dialog.getNextNumber() offsety = dialog.getNextNumber() interval = dialog.getNextNumber() linescan_overlay = LineScanOverlayMetadata( (p1x, p1y), (p2x, p2y), (offsetx, offsety), interval) metadatas.append(linescan_overlay) roi = linescan_overlay.generateOverlayRoi() imp.setRoi(roi) IJ.run("Draw", "stack") if dialog.wasOKed(): runagain = False elif dialog.wasCanceled(): return sd = SaveDialog("Save as AVI...", os.path.splitext(imp.getTitle())[0], "line scan overlay.avi") if sd.getFileName is not None: metadatas[0].save_to_json( os.path.join( sd.getDirectory(), os.path.splitext(os.path.basename(sd.getFileName()))[0] + "line scan metadata.json")) if len( metadatas ) > 1: # append: multiple writes=slow, but easiest way based on existing framework for midx in range(1, len(metadatas)): metadatas[midx].save_to_json(os.path.join( sd.getDirectory(), os.path.splitext(os.path.basename(sd.getFileName()))[0] + "line scan metadata.json"), append=True) IJ.saveAs( imp, "Tiff", os.path.join( sd.getDirectory(), os.path.splitext(os.path.basename(sd.getFileName()))[0] + " + line scan ROI, no timestamp.tif")) IJ.run( imp, "Label...", "format=00:00:00 starting=0 interval=" + str(interval) + " x=5 y=20 font=18 text=[] range=1-" + str(imp.getNFrames())) IJ.run( imp, "AVI... ", "compression=None frame=10 save=[" + os.path.join(sd.getDirectory(), (os.path.splitext(sd.getFileName())[0] + " + line scan ROI.avi")) + "]") IJ.saveAs( imp, "Tiff", os.path.join( sd.getDirectory(), os.path.splitext(os.path.basename(sd.getFileName()))[0] + " + line scan ROI.tif"))
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 batch_open_images(pathImage, file_typeImage, name_filterImage=None): if isinstance(pathImage, File): pathImage = pathImage.getAbsolutePath() def check_filter(string): '''This function is used to check for a given filter. It is possible to use a single string or a list/tuple of strings as filter. This function can access the variables of the surrounding function. :param string: The filename to perform the filtering on. ''' if name_filterImage: # The first branch is used if name_filter is a list or a tuple. if isinstance(name_filterImage, (list, tuple)): for name_filter_ in name_filterImage: if name_filter_ in string: # Exit the function with True. return True else: # Next iteration of the for loop. continue # The second branch is used if name_filter is a string. elif isinstance(name_filterImage, string): if name_filterImage in string: return True else: return False return False else: # Accept all files if name_filter is None. return True def check_type(string): '''This function is used to check the file type. It is possible to use a single string or a list/tuple of strings as filter. This function can access the variables of the surrounding function. :param string: The filename to perform the check on. ''' if file_typeImage: # The first branch is used if file_type is a list or a tuple. if isinstance(file_typeImage, (list, tuple)): for file_type_ in file_typeImage: if string.endswith(file_type_): # Exit the function with True. return True else: # Next iteration of the for loop. continue # The second branch is used if file_type is a string. elif isinstance(file_typeImage, string): if string.endswith(file_typeImage): return True else: return False return False # Accept all files if file_type is None. else: return True # We collect all files to open in a list. path_to_Image = [] # Replacing some abbreviations (e.g. $HOME on Linux). path = os.path.expanduser(pathImage) path = os.path.expandvars(pathImage) # If we don't want a recursive search, we can use os.listdir(). for directory, dir_names, file_names in os.walk(pathImage): # We are only interested in files. for file_name in file_names: # The list contains only the file names. # The full path needs to be reconstructed. full_path = os.path.join(directory, file_name) # Both checks are performed to filter the files. if check_type(file_name): if check_filter(file_name) is False: # Add the file to the list of images to open. path_to_Image.append([ full_path, os.path.basename(os.path.splitext(full_path)[0]) ]) Images = [] for img_path, file_name in path_to_Image: imp = IJ.openImage(img_path) maskimage = ops.run("create.img", imp) cursor = maskimage.localizingCursor() imp.show() IJ.run("Select None") overlay = imp.getOverlay() if overlay == None: overlay = Overlay() imp.setOverlay(overlay) else: overlay.clear() imp.updateAndDraw() impY = imp.getHeight() impX = imp.getWidth() print(impY, impX) rm = RoiManager.getInstance() if not rm: rm = RoiManager() rm.runCommand("reset") WaitForUserDialog("Select the landmark and the second point").show() rm.runCommand("Add") roi_points = rm.getRoisAsArray() for Roi in roi_points: xpoints = Roi.getPolygon().xpoints ypoints = Roi.getPolygon().ypoints print(xpoints, ypoints) print('Start Landmark', xpoints[0], ypoints[0]) fixedpointX = xpoints[0] fixedpointY = ypoints[0] print('End Landmark', xpoints[1], ypoints[1]) IJ.makeLine(xpoints[0], ypoints[0], xpoints[1], ypoints[1]) gui = GenericDialog("Rotation Angle") gui.addNumericField("Choose Angle", 15, 0) gui.showDialog() if gui.wasOKed(): rotateangle = gui.getNextNumber() IJ.run("Rotate...", "angle=" + str(int(float(rotateangle)))) rm.runCommand("reset") overlay = imp.getOverlay() rm.runCommand("Add") roi_points = rm.getRoisAsArray() for Roi in roi_points: xpoints = Roi.getPolygon().xpoints ypoints = Roi.getPolygon().ypoints print(xpoints, ypoints) print('Rotated Start Landmark', xpoints[0], ypoints[0]) print('Rotated End Landmark', xpoints[1], ypoints[1]) slope = (ypoints[1] - ypoints[0]) / (xpoints[1] - xpoints[0] + 1.0E-20) intercept = fixedpointY - slope * fixedpointX print(fixedpointX, fixedpointY) print('Slope', slope, 'Intercept', intercept) XwY0 = -intercept / slope YxwY0 = slope * XwY0 + intercept XwYmax = (impY - intercept) / slope YxwYmax = slope * XwYmax + intercept YwX0 = intercept XywX0 = (YwX0 - intercept) / slope YwXmax = impX * slope + intercept XxwXmax = (YwXmax - intercept) / slope rm.runCommand("reset") if XwY0 > 0: lineROIA = Line(fixedpointX, fixedpointY, XwY0, YxwY0) lineROIB = Line(fixedpointX, fixedpointY, XwYmax, YxwYmax) overlay.add(lineROIA) overlay.add(lineROIB) if XwY0 < 0: lineROIA = Line(fixedpointX, fixedpointY, XywX0, YwX0) lineROIB = Line(fixedpointX, fixedpointY, XxwXmax, YwXmax) overlay.add(lineROIA) overlay.add(lineROIB) while cursor.hasNext(): cursor.fwd() X = cursor.getDoublePosition(0) Y = cursor.getDoublePosition(1) if abs(Y - slope * X - intercept) <= 4: cursor.get().set(0) else: cursor.get().set(1) labeling = ops.labeling().cca(maskimage, StructuringElement.EIGHT_CONNECTED) # get the index image (each object will have a unique gray level) labelingIndex = labeling.getIndexImg() dataImg = ds.create(labelingIndex) location = ls.resolve( str(savedir) + '/' + file_name + '.' + file_type_image) dio.save(dataImg, location) imp.close()
imp.setPosition(1, eventOutL, 1) else: eventOutL = frames + slider3_feedback + 1 + slider2_feedback * ( ch * frames) + evt * (zplanes * ch * frames) imp2.setPosition(1, eventOutL, 1) # Define the pre-conditions for loading the data, default values represent my normal acquisition parameters only the loop has to be set, the rest is read from metadata psgd = GenericDialog("Pre-Set") psgd.addCheckbox( "Images open?", False ) # if your images are already open as a virtual stack, you can avoid to load again psgd.showDialog() if psgd.wasOKed(): choiceIm = psgd.getCheckboxes().get(0).getState() # load data as virtual stack, simple image stack if choiceIm == False: IJ.run("Close All", "") impDir = OpenDialog("Select the 6D dataset").getPath() impDir = impDir.replace("\\", "/") IJ.run( "Bio-Formats", "open=" + impDir + " color_mode=Default display_metadata rois_import=[ROI manager] view=[Standard ImageJ] stack_order=Default use_virtual_stack" ) #define ImagePlus to variable and remove path from title imp = WM.getCurrentImage()
else: # List column headers table = tableWindow.getResultsTable() headers = table.getHeadings() # Generate dialog with dropdown for column selection dialog = GenericDialog("PieChart from table column") dialog.addChoice("Data column", headers, headers[0]) dialog.addMessage( """Hover the mouse over the plot to view absolute and relative (%) values\n Right-click to set colors, export to PNG...\n Note: BarCharts usually provide better distinction than PieCharts for sectors with similar sizes (see Help).""" ) dialog.addHelp(r"https://www.data-to-viz.com/caveat/pie.html") dialog.showDialog() # Generate PieChart with data column if dialog.wasOKed(): # Get the data column as string selectedHeader = dialog.getNextChoice() column = table.getColumnAsVariables(selectedHeader) columnString = [str(item)[1:-1] for item in column] # [1:-1] to remove the "" # Make the PieChart for this data column if columnString: chart = PieChart(selectedHeader, columnString) chart.showFrame("PieChart")
def main_interactive(): """The main routine for running interactively.""" log.info('Running in interactive mode.') (base, fname) = ui_get_input_file() if (base is None): return log.warn("Parsing project file: %s" % (base + fname)) IJ.showStatus("Parsing experiment file...") mosaics = fv.FluoViewMosaic(join(base, fname), runparser=False) IJ.showStatus("Parsing mosaics...") progress = 0.0 count = len(mosaics.mosaictrees) step = 1.0 / count for subtree in mosaics.mosaictrees: IJ.showProgress(progress) mosaics.add_mosaic(subtree) progress += step IJ.showProgress(progress) IJ.showStatus("Parsed %i mosaics." % len(mosaics)) dialog = GenericDialog('FluoView OIF / OIB Stitcher') if len(mosaics) == 0: msg = ("Couldn't find any (valid) mosaics in the project file.\n" " \n" "Please make sure to have all files available!\n" " \n" "Will stop now.\n") log.warn(msg) dialog.addMessage(msg) dialog.showDialog() return msg = "------------------------ EXPORT OPTIONS ------------------------" dialog.addMessage(msg) formats = ["OME-TIFF", "ICS/IDS"] dialog.addChoice("Export Format", formats, formats[0]) dialog.addCheckbox("separate files by Z slices (OME-TIFF only)?", False) msg = "------------------------ EXPORT OPTIONS ------------------------" dialog.addMessage(msg) dialog.addMessage("") dialog.addMessage("") msg = gen_mosaic_details(mosaics) log.warn(msg) msg += "\n \nPress [OK] to write tile configuration files\n" msg += "and continue with running the stitcher." dialog.addMessage(msg) dialog.showDialog() opts = {} if dialog.getNextChoice() == 'ICS/IDS': opts['export_format'] = '".ids"' else: opts['export_format'] = '".ome.tif"' if dialog.getNextBoolean() == True: opts['split_z_slices'] = 'true' code = imagej.gen_stitching_macro_code(mosaics, 'templates/stitching', path=base, tplpath=imcftpl, opts=opts) log.warn("============= generated macro code =============") log.warn(flatten(code)) log.warn("============= end of generated macro code =============") if dialog.wasOKed(): log.warn('Writing stitching macro.') imagej.write_stitching_macro(code, fname='stitch_all.ijm', dname=base) log.warn('Writing tile configuration files.') imagej.write_all_tile_configs(mosaics, fixsep=True) log.warn('Launching stitching macro.') IJ.runMacro(flatten(code))
IJ.showStatus("Computing...") computedImage = reduce(self.addImages,imgList) computedImage.show() IJ.showStatus("Ready") ## Main body of script opener = OpenDialog("Select parent LSM file...") parentLSMFilePath = opener.getPath() if (parentLSMFilePath is not None): stackInfo = parse_tile_info_file(parentLSMFilePath + "_tiles/tile_info.txt") channelTexts = map(lambda x: str(x), filter(lambda x:os.path.isfile(parentLSMFilePath+"_tiles/objects/C"+str(x)+".objects.keep.unique.csv"),range(1,stackInfo[0]+1))) gd = GenericDialog("Specify parameters...") gd.addChoice("Which_channel",channelTexts,channelTexts[0]) gd.showDialog() if gd.wasOKed(): channel = int(gd.getNextChoice()) ## Obtains global coordinate system for tiles scale_info = estimate_scale_multiplier(parentLSMFilePath+"_tiles/tile_1.ome.tif",parentLSMFilePath+"_tiles/resized/tile_1.tif") ## Parses each of the object files objectDB = [[] for x in range(4)] objectDB[0] = parse_object_file_into_db(parentLSMFilePath+"_tiles/objects/C"+str(channel)+".objects.keep.contained.csv") objectDB[1] = parse_object_file_into_db(parentLSMFilePath+"_tiles/objects/C"+str(channel)+".objects.keep.duplicated.csv") objectDB[2] = parse_object_file_into_db(parentLSMFilePath+"_tiles/objects/C"+str(channel)+".objects.keep.restitched.csv") objectDB[3] = parse_object_file_into_db(parentLSMFilePath+"_tiles/objects/C"+str(channel)+".objects.keep.unique.csv") ## Converts object global coordinates to rescaled coordinates for i in range(len(objectDB)): for j in range(len(objectDB[i])):
def get_ok(): gd = GenericDialog("Caution") gd.addMessage("Do you want to overwrite the files ? ") gd.showDialog() return gd.wasOKed()
DIALOG = True if (DIALOG): # ----------------- DIALOG TO FILL GLOBAL PARAMETERS ----- gui = GenericDialog("Parameters") gui.addStringField("NGROK Server address :", "0.tcp.ngrok.io") gui.addStringField("PORT :", "") gui.showDialog() HOST = gui.getNextString() PORT = int(gui.getNextString()) gui = GenericDialogPlus("Parameters") gui.addFileField("Select a model file in Keras format (*.h5) : ", "") gui.showDialog() if gui.wasOKed(): LOCAL_MODEL_FILENAME = gui.getNextString() gui = GenericDialogPlus("Parameters") gui.addFileField("Select a python script file to upload on the server (*.py) : ", "") gui.showDialog() if gui.wasOKed(): LOCAL_PREDICTION_SCRIPT = gui.getNextString() jsch=JSch() # SSH Connection to DeepLearning server IJ.log("-- Connection to FiGoCo Server") time0 = time.time() session=jsch.getSession("root", HOST, PORT);
measurements_filename = imp_title[:-4] IJ.saveAs("Results", "{}{}.csv".format(path, measurements_filename)) IJ.selectWindow("Results") IJ.run("Close") IJ.log("Measurements saved at {}{}.csv".format(path, measurements_filename)) # Close the active image so IJ can move on to the next imp.close() n_images = WindowManager.getImageCount() i = 0 while i < n_images: measure_rois() i += 1 # Clear ROI manager (after OKing with user) so that there aren't still # ROIs that will be used in next measurement gd = GenericDialog("ROI deletion warning") gd.addMessage("Do you wish to clear current ROIs?") gd.enableYesNoCancel() choice = gd.showDialog() roim = RoiManager.getInstance() if gd.wasCanceled(): pass elif gd.wasOKed(): roim.reset() else: print("NO")
# Asks for parameters gd = GenericDialog("Set Parameters...") gd.addNumericField("Start tile:",1,0) gd.addNumericField("Finish tile:",9,0) gd.addNumericField("Final disk space / Initial disk space:",0.25,2) gd.addNumericField("Step size (higher is faster but uses more memory):",10,0) gd.showDialog() startTile = int(gd.getNextNumber()) finishTile = int(gd.getNextNumber()) ratioRaw = gd.getNextNumber() ratio = math.sqrt(ratioRaw) stepSize = int(gd.getNextNumber()) # Performs scaling if (gd.wasOKed()): anchorTiles = range(startTile,finishTile+1,stepSize) print anchorTiles for i in anchorTiles: if (i+stepSize-1 > finishTile): lastAnchorTile = finishTile else: lastAnchorTile = i+stepSize-1 iterTiles = range(i,lastAnchorTile+1) params = "open=[" + theFilePath + "] color_mode=Default view=Hyperstack stack_order=XYCZT series_list=" + str(i) + "-" + str(lastAnchorTile) print params IJ.run("Bio-Formats Importer", params) imageIDList = WindowManager.getIDList() if (len(imageIDList) == len(iterTiles)): count = 0
uGshapemax = gdp.getNextNumber() uOverlap = gdp.getNextNumber() uExclude = gdp.getNextChoice() # Files will automatically be output to a new Fiji_Analysis directory. If this directory already exists, files will be overwritten. This checks to make sure the directory does not yet exist. if path.exists(outdir + File.separatorChar + "Fiji_Analysis") and path.isdir(outdir + File.separatorChar + "Fiji_Analysis"): gdchk = GenericDialog("WARNING") gdchk.addMessage( "Analysis folder already exists. Choose a different directory to avoid overwritng your current data" ) gdchk.hideCancelButton() gdchk.showDialog() print "Analysis folder already exists. Choose a new directory to avoid overwriting your current analysis" uknow = gdchk.wasOKed() if uknow == True: IJ.getImage() #Creates Fiji_Analysis directory. File(outdir + File.separatorChar + "Fiji_Analysis").mkdir() analysisOut = outdir + File.separatorChar + "Fiji_Analysis" print analysisOut inputPaths = [path_wt, path_dic, path_mut, path_bg] # Since the script is critically depedent on file input order, files are duplicated and saved with easily referenced names in the new Directory. 0 = WT, 1 = DIC, 2 = MUT, 3 = BG. ALWAYS. newPaths = [] for p in inputPaths: IJ.open(p) tmp = IJ.openImage(p)