def getOptions(imp): gd = GenericDialog("Correct 2D/3D Drift Options") channels = [] for ch in range(1, imp.getNChannels()+1 ): channels.append(str(ch)) gd.addChoice("Channel for registration:", channels, channels[0]) gd.addCheckbox("Correct only x & y (for 3D data):", False) gd.addCheckbox("Multi_time_scale computation for enhanced detection of slow drifts?", False) gd.addCheckbox("Sub_pixel drift correction (possibly needed for slow drifts)?", False) gd.addCheckbox("Edge_enhance images for possibly improved drift detection?", False) gd.addNumericField("Only consider pixels with values larger than:", 0, 0) gd.addNumericField("Lowest z plane to take into account:", 1, 0) gd.addNumericField("Highest z plane to take into account:", imp.getNSlices(), 0) gd.addCheckbox("Use virtualstack for saving the results to disk to save RAM?", False) gd.addCheckbox("Only compute drift vectors?", False) gd.addMessage("If you put a ROI, drift will only be computed in this region;\n the ROI will be moved along with the drift to follow your structure of interest.") gd.showDialog() if gd.wasCanceled(): return channel = gd.getNextChoiceIndex() + 1 # zero-based correct_only_xy = gd.getNextBoolean() multi_time_scale = gd.getNextBoolean() subpixel = gd.getNextBoolean() process = gd.getNextBoolean() background = gd.getNextNumber() z_min = gd.getNextNumber() z_max = gd.getNextNumber() virtual = gd.getNextBoolean() only_compute = gd.getNextBoolean() return channel, virtual, multi_time_scale, subpixel, process, background, z_min, z_max, only_compute, correct_only_xy
def start_masking_menu(): wlist = WindowManager.getImageTitles() gd = GenericDialog('Masking - Setup') gd.setCancelLabel('Exit') gd.addChoice('Create mask from', wlist, wlist[0]) gd.addNumericField("Gaussian blur:", 0, 1) gd.addNumericField("Fixed threshold:", 0, 0) gd.addCheckbox('Use automatic thresholding', False) gd.addChoice('Method', ['Default', 'Huang', 'Otsu', 'Yen'], 'Default') gd.showDialog() if gd.wasCanceled(): return False pdic = {} pdic['sel_win'] = gd.getNextChoice() pdic['sigma'] = gd.getNextNumber() pdic['threshold'] = gd.getNextNumber() pdic['use_auto'] = gd.getNextBoolean() pdic['thresh_method'] = gd.getNextChoice() return pdic
def main(): properties = ImageProperties(imp) # Create a GenericDialog to configure renaming: gd = GenericDialog('Gatan Reamer') gd.addMessage('Modifying: %s' % (imp.getTitle(),)) gd.addMessage('Recorded: %s' % (properties.date.toString(),)) gd.addNumericField('Exposure time', properties.exposure, 4, field_width, 's') gd.addNumericField('Magnification:', properties.magnification, 0, field_width, 'x') mag_units = ('kx', 'x') gd.addChoice('Magnification unit:', mag_units, mag_units[0]) gd.addMessage('The actual magnification is %.2f times larger.' % (properties.mag_factor,)) gd.addCheckbox('Use actual magnification:', False) gd.addMessage('') gd.addNumericField('Energy loss:', properties.energyloss, 1, field_width, 'eV') gd.addStringField('Date:', properties.date_string, field_width) gd.addStringField('original name:', properties.name, field_width_long) gd.addStringField('Filename format', default_format_str, field_width_long) gd.showDialog() if not gd.wasCanceled(): # Edit the properties to consiter user choices: properties.exposure = gd.getNextNumber() mag = gd.getNextNumber() properties.mag_unit = gd.getNextChoice() if gd.getNextBoolean(): properties.calc_mag(mag) properties.energyloss = gd.getNextNumber() properties.date_string = gd.getNextString() properties.name = gd.getNextString() format_str = gd.getNextString() # Chenge the title: imp.setTitle(format_str % properties.to_dict())
def setupDialog(imp): gd = GenericDialog("Toolbox options") gd.addMessage("Imagej toolbox, you are analyzing: " + imp.getTitle()) calibration = imp.getCalibration() if (calibration.frameInterval > 0): default_interval = calibration.frameInterval default_timeunit = calibration.getTimeUnit() else: default_interval = 10 default_timeunit = "sec" gd.addNumericField("Frame interval:", default_interval, 2) # show 2 decimals # gd.addCheckbox("Do you want to use a gliding window?", True) # gd.addCheckbox("Project hyperStack? (defaluts to projecting current channel only)", False) # gd.addStringField("time unit",default_timeunit, 3) # gd.addSlider("Start compacting at frame:", 1, imp.getNFrames(), 1) # gd.addSlider("Stop compacting at frame:", 1, imp.getNFrames(), imp.getNFrames()) # gd.addNumericField("Number of frames to project in to one:", 3, 0) # show 0 decimals gd.addChoice('Method to use for stack background filtering:', methods_as_strings, methods_as_strings[5]) gd.showDialog() if gd.wasCanceled(): IJ.log("User canceled dialog!") return return gd
def getOptions(imp): gd = GenericDialog("Correct 3D Drift Options") channels = [] for ch in range(1, imp.getNChannels()+1 ): channels.append(str(ch)) methods = ["phase_correlation","center_of_mass"] gd.addChoice("Channel for registration:", channels, channels[0]) gd.addChoice("Method for registration:", methods, methods[1]) gd.addNumericField("Background value:", 0, 0) gd.addCheckbox("Multi_time_scale computation for enhanced detection of slow drifts?", False) gd.addCheckbox("Sub_pixel drift correction (possibly needed for slow drifts)?", False) gd.addCheckbox("Edge_enhance images for possibly improved drift detection?", False) gd.addCheckbox("Use virtualstack for saving the results to disk to save RAM?", False) gd.addCheckbox("Drift correct only data inside ROI?", False) gd.addCheckbox("Only compute drift vectors?", False) gd.addMessage("If you put a ROI, drift will only be computed in this region;\n the ROI will be moved along with the drift to follow your structure of interest.") gd.addSlider("z_min of ROI", 1, imp.getNSlices(), 1) gd.addSlider("z_max of ROI", 1, imp.getNSlices(), imp.getNSlices()) gd.showDialog() if gd.wasCanceled(): return channel = gd.getNextChoiceIndex() + 1 # zero-based method = gd.getNextChoiceIndex() + 1 # zero-based bg_value = gd.getNextNumber() multi_time_scale = gd.getNextBoolean() subpixel = gd.getNextBoolean() process = gd.getNextBoolean() virtual = gd.getNextBoolean() only_roi = gd.getNextBoolean() only_compute = gd.getNextBoolean() roi_z_min = int(gd.getNextNumber()) roi_z_max = int(gd.getNextNumber()) return channel, method, bg_value, virtual, multi_time_scale, subpixel, process, only_roi, only_compute, roi_z_min, roi_z_max
def getOptions(): global listener, xlist, ylist, zlist, manager gd = GenericDialog("Target Selection") gd.addChoice('type', ['point', 'circle', 'spiral'], 'point') gd.addNumericField(" power (%)", 85, 0) gd.addNumericField(" duration (ms)", 1, 0) gd.addNumericField(" radius(circle/spiral)", 5, 0) gd.addNumericField(" # revolutions (circle/spiral)", 3, 0) gd.addNumericField( " add CAMERA_TRIGGER after every (entries)", 1, 0) gd.addNumericField(" Prewait between entries (ms)", 5000, 0) gd.addNumericField(" Z-start of stack (um)", 0, 0) gd.addNumericField(" Z-step of stack (um)", 5, 0) gd.addMessage('Press ENTER to save\n') gd.addMessage('Press ESC to restart\n') gd.showDialog() profileType = gd.getNextChoice() power = gd.getNextNumber() duration = gd.getNextNumber() r = gd.getNextNumber() Nturns = gd.getNextNumber() camTriggerEvery = gd.getNextNumber() prewait = gd.getNextNumber() zStart = gd.getNextNumber() zStep = gd.getNextNumber() if gd.wasCanceled(): IJ.setTool(Toolbar.RECTANGLE) return else: return r, power, profileType, duration, Nturns, camTriggerEvery, zStart, zStep, prewait
def getRefChannel(channels, text = 'Reference Channel'): #dialog prompt to choose the reference channel gd = GenericDialog(text) gd.addChoice("output as", channels, channels[0]) gd.showDialog() if gd.wasCanceled(): print "User canceled dialog!" return return gd.getNextChoice()
def Resize(imp): gd = GenericDialog("Image size") scales = ["1024","2048","4096"] gd.addChoice("Choose image size",scales,scales[1]) gd.showDialog() scale_choice = gd.getNextChoice() IJ.run(imp,"Scale...", "x=- y=- z=1.0 width="+scale_choice+" height="+scale_choice+" interpolation=Bilinear average process create title=Scaled") scaled_imp = WindowManager.getImage("Scaled") return scaled_imp
def choose_analysis_mode(params): """present UI for choosing how cells should be identified""" dialog = GenericDialog("Analysis methods") dialog.addMessage("Please choose how cell shape anlaysis should proceed:") dialog.addChoice("Analysis mode", params.list_analysis_modes(), params.last_analysis_mode) dialog.showDialog() if dialog.wasCanceled(): raise KeyboardInterrupt("Run canceled") return dialog.getNextChoice()
def getRef(self, event): """ Dialog to update ref image attribute when get_ref button is pressed """ self.checkImages() gd = GenericDialog("Choose a reference image") gd.addChoice("Reference image", [Image.title for Image in self.Images.values()], self.Images.values() [0].title) # add all Image instances to a drop-down list gd.showDialog() ref_image_name = gd.getNextChoice() ref_image_ID = WM.getImage(ref_image_name).getID() self.ref_image = self.Images[ ref_image_ID] # update ref_image attribute IJ.log("Reference image is " + self.ref_image.title)
def getChannels(): gd = GenericDialog( "Select stack's channels" ) # print gd.getModalityType() # gd.setModal( False ) # print gd.getModalityType() color = ["red", "green", "blue"] gd.addChoice("Channel for mask", color, color[2]) gd.addChoice("Channel for particles", color, color[1]) gd.showDialog() maskChannel = gd.getNextChoice() partChannel = gd.getNextChoice() if gd.wasCanceled(): sys.exit() return maskChannel, partChannel
def create_selection_dialog(image_titles, defaults, title='Select images for processing'): gd = GenericDialog(title) # The build in function enumerate() returns two values: # The index and the value stored in the tuple/list. for index, default in enumerate(defaults): # for each loop we add a new choice element to the dialog. gd.addChoice('Image_'+ str(index + 1), image_titles, image_titles[default]) gd.showDialog() if gd.wasCanceled(): return None # This function returns a list. # _ is used as a placeholder for values we don't use. # The for loop is used to call gd.getNextChoiceIndex() len(defaults) times. return [gd.getNextChoiceIndex() for _ in defaults]
def create_selection_dialog(image_titles, defaults, title='Select images for processing'): """ Show a dialog to select the images to process and return a list of the selected ones (index). :param image_titles: A list of image titles presented for selection. :param defaults: The titles to be selected by default. The length of this list defines the number of selectable images. :param title: the title of the dialog (default 'Select images for processing'). """ dialog = GenericDialog(title) for index, default in enumerate(defaults): dialog.addChoice('Image_'+ str(index + 1), image_titles, image_titles[default]) dialog.showDialog() if dialog.wasCanceled(): return None return [dialog.getNextChoiceIndex() for _ in defaults]
def getOptions(imp): gd = GenericDialog("Correct 3D Drift Options") channels = [] for ch in range(1, imp.getNChannels()+1 ): channels.append(str(ch)) gd.addMessage("Select a channel to be used for the registration.") gd.addChoice(" channel:", channels, channels[0]) gd.addCheckbox("Use virtualstack?", False) gd.addMessage("This will store the registered hyperstack as an image sequence and\nshould be used if free RAM is less than 2X the size of the hyperstack. ") gd.showDialog() if gd.wasCanceled(): return channel = gd.getNextChoiceIndex() + 1 # zero-based virtual = gd.getNextBoolean() return channel, virtual
def getOptions(options, image): if 'channel' not in options: channels = [] for ch in range(1, image.getNChannels() + 1): channels.append("Channel " + "%i" % ch) dialog = GenericDialog("Select deconvolution parameters") dialog.addChoice("Channel to process", channels, None) dialog.addNumericField("Regularization parameter", 0.01, 2) dialog.addNumericField("Number of iterations", 50, 0) dialog.showDialog() if dialog.wasCanceled(): sys.exit(1) options['channel'] = dialog.getNextChoiceIndex() options['regparam'] = dialog.getNextNumber() options['iterations'] = dialog.getNextNumber() return options
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 getOptionsDialog(self, imp): thr_methods = ["None", "Default", "Huang", "Intermodes", "IsoData", "Li", "MaxEntropy","Mean", "MinError(I)", "Minimum", "Moments", "Otsu", "Percentile", "RenyiEntropy", "Shanbhag" , "Triangle", "Yen"] gd = GenericDialog("Please select channels to collocalize") for i in range(1, imp.getNChannels() + 1): gd.addChoice("Threshold method for channel %i" % i, thr_methods, "None") gd.showDialog() if gd.wasCanceled(): self.exit() channels = [] for i in range(1, imp.getNChannels() + 1): method = gd.getNextChoice() self.methods.append(method) if method != "None": channels.append(i) for x in channels: for y in channels: if x < y: self.pairs.append((x, y))
def getThresholds(): thresholds = {} gd = GenericDialog("Threshold options") gd.addChoice("How would you like to set your thresholds?", ["default", "use threshold csv file"], "default") gd.showDialog() choice = gd.getNextChoice() log.write("Option: " + choice + "\n") if choice == "use threshold csv file": path = OpenDialog("Open the thresholds csv file") log.write("File used: " + path.getPath() + "\n") with open(path.getPath()) as csvfile: reader = csv.DictReader(csvfile) for row in reader: thresholds = row return thresholds
def getSegmentationParameters(): gd = GenericDialog('Enter segmentation parameters') gd.addMessage( 'Slice selection thresholds (percentiles of average intensity): \n \n') gd.addNumericField('Lower threshold', 0.25, 2) gd.addNumericField('Upper threshold', 0.65, 2) gd.addMessage('Image processing parameters for cells: \n \n') gd.addNumericField('Width of Gaussian filter [px]', 4, 0) gd.addChoice('Auto threshold method', [ 'Huang', 'Huang2', 'Intermodes', 'IsoData', 'Li', 'MaxEntropy', 'Mean', 'MinError(I)', 'Minimum', 'Moments', 'Otsu', 'Percentile', 'RenyiEntropy', 'Shanbhag', 'Triangle', 'Yen' ], 'Triangle') gd.addStringField('Particle size range [px^2]', '10000-5000000', 16) gd.addStringField('Particle circularity range', '0.20-1.00') gd.addMessage('Image processing parameters for nuclei: \n \n') gd.addNumericField('Width of Gaussian filter [px]', 4, 0) gd.addChoice('Auto threshold method', [ 'Huang', 'Huang2', 'Intermodes', 'IsoData', 'Li', 'MaxEntropy', 'Mean', 'MinError(I)', 'Minimum', 'Moments', 'Otsu', 'Percentile', 'RenyiEntropy', 'Shanbhag', 'Triangle', 'Yen' ], 'Otsu') gd.addStringField('Particle size range [px^2]', '3500-10000', 16) gd.addStringField('Particle circularity range', '0.5-1.00') gd.addCheckbox('Run in testing mode?', 0) gd.showDialog() if gd.wasCanceled(): print 'User canceled dialog!' # Read out inputs params = {} params['avgI_low'] = gd.getNextNumber() params['avgI_high'] = gd.getNextNumber() params['cellsigma'] = int(gd.getNextNumber()) params['cellmethod'] = gd.getNextChoice() params['cellsize'] = gd.getNextString() params['cellcircularity'] = gd.getNextString() params['nucsigma'] = int(gd.getNextNumber()) params['nucmethod'] = gd.getNextChoice() params['nucsize'] = gd.getNextString() params['nuccircularity'] = gd.getNextString() params['test'] = gd.getNextBoolean() return params
def get_color(nChannel=n_Channel): color_strings = [ "Green", "Magenta", "Cyan", "Blue", "Red", "Yellow", "Orange", "Gray", "Black" ] gd = GenericDialog("Set Colors") for i in range(nChannel): gd.addChoice("Channel {}".format(i + 1), color_strings, color_strings[i]) gd.showDialog() if gd.wasCanceled(): return else: selected_colours = [gd.getNextChoice() for _ in range(nChannel)] return selected_colours
def choose_analysis_mode(params): """present UI for choosing how cells should be identified""" dialog = GenericDialog("Analysis methods") dialog.addMessage("Please choose how cell shape anlaysis should proceed:") dialog.addChoice("Analysis mode: ", params.list_analysis_modes(), params.last_analysis_mode) dialog.addMessage("") dialog.addChoice("GFP segmentation method: ", AutoThresholder.getMethods(), params.last_threshold_method) dialog.addNumericField("Minimum cell area (um" + _squared + "): ", params.last_minimum_cell_area_um2, 0) # dl = AnalysisModeListener() # dialog.addDialogListener(dl) dialog.showDialog() if dialog.wasCanceled(): print("Run canceled") return None, None, None return dialog.getNextChoice(), dialog.getNextChoice( ), dialog.getNextNumber()
def getOptions(): gd = GenericDialog("Loci Distance to compartment option") gd.addChoice("Compartment Channel", ["1","2","3","4"], "1") gd.addNumericField("Compartment Threshold",0.60,2) gd.addChoice("Loci Channel", ["1","2","3","4"], "2") gd.addNumericField("Compartment Threshold",0.60,2) gd.showDialog() # if gd.wasCanceled(): print "User canceled dialog!" return # # Read out the options speck_ch= int(gd.getNextChoice()) speck_th = gd.getNextNumber() loci_ch= int(gd.getNextChoice()) loci_th = gd.getNextNumber() return speck_ch,speck_th, loci_ch, loci_th
def getOptions(): gd = GenericDialog("Options") gd.addStringField("name", "Untitled") gd.addNumericField("alpha", 0.25, 2) # show 2 decimals gd.addCheckbox("optimize", True) types = ["8-bit", "16-bit", "32-bit"] gd.addChoice("output as", types, types[2]) gd.addSlider("scale", 1, 100, 100) gd.showDialog() # if gd.wasCanceled(): print "User canceled dialog!" return # Read out the options name = gd.getNextString() alpha = gd.getNextNumber() optimize = gd.getNextBoolean() output = gd.getNextChoice() scale = gd.getNextNumber() return name, alpha, optimize, output, scale
def getOptions(imp): gd = GenericDialog("Correct 3D Drift Options") channels = [] for ch in range(1, imp.getNChannels()+1 ): channels.append(str(ch)) gd.addChoice("Channel for registration:", channels, channels[0]) gd.addCheckbox("Multi_time_scale computation for enhanced detection of slow drifts?", False) gd.addCheckbox("Sub_pixel drift correction (possibly needed for slow drifts)?", False) gd.addCheckbox("Edge_enhance images for possibly improved drift detection?", False) gd.addCheckbox("Use virtualstack for saving the results to disk to save RAM?", False) gd.addMessage("If you put a ROI, drift will only be computed in this region;\n the ROI will be moved along with the drift to follow your structure of interest.") gd.showDialog() if gd.wasCanceled(): return channel = gd.getNextChoiceIndex() + 1 # zero-based multi_time_scale = gd.getNextBoolean() subpixel = gd.getNextBoolean() process = gd.getNextBoolean() virtual = gd.getNextBoolean() dt = gd.getNextNumber() return channel, virtual, multi_time_scale, subpixel, process
def getNames(): names = {} gd = GenericDialog("Naming options") gd.addChoice("How would you like to name your results for each well?", ["default", "use name convention csv file"], "default") gd.showDialog() choice = gd.getNextChoice() log.write("Option: " + choice + "\n") if choice == "use name convention csv file": path = OpenDialog("Open the names csv file") log.write("File used: " + path.getPath() + "\n") with open(path.getPath()) as csvfile: reader = csv.DictReader(csvfile) for row in reader: names[row['Row']] = row return names
def get_setup(): ''' Returns the drift correction mode and three image. The order of return values is drift detection mode, pre-edge 1, pre-edge 2, post-edge. ''' options = drift.get_options() modes = drift.get_modes() dialog = GenericDialog('3-window-method setup') dialog.addMessage('Select the mode for drift correction\n' + 'and the images to process.') dialog.addChoice('Mode:', options, options[0]) image_ids = WindowManager.getIDList() if not image_ids or len(image_ids) < 2: return [None]*4 image_titles = [WindowManager.getImage(id).getTitle() for id in image_ids] dialog.addMessage('Post-edge is divided by the pre-edge.') dialog.addChoice('Pre-edge 1', image_titles, image_titles[0]) dialog.addChoice('Pre-edge 2', image_titles, image_titles[1]) dialog.addChoice('Post-edge', image_titles, image_titles[2]) dialog.showDialog() if dialog.wasCanceled(): return [None]*4 mode = modes[dialog.getNextChoiceIndex()] img1 = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()]) img2 = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()]) img3 = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()]) return mode, img1, img2, img3
def getOptions(): global listener, xlist, ylist, zlist, manager gd = GenericDialog("Target Selection") gd.addMessage('Mandatory parameters\n') gd.addChoice('type', ['point', 'circle', 'spiral'], 'point') gd.addNumericField(" power (%)", 85, 0) gd.addNumericField(" duration (millisec)", 3, 0) gd.addNumericField(" interval between entries (ms)", 5000, 0) gd.addNumericField(" Z-start of stack (microns)", 0, 0) gd.addNumericField(" Z-step of stack (microns)", 5, 0) gd.addMessage('Optional\n') gd.addNumericField(" radius of a circle/spiral", 5, 0) gd.addNumericField(" num. of turns per circle/spiral", 3, 0) gd.addNumericField(" take image after every .. entries", 1, 0) gd.addNumericField(" add offset to X coordinates", 0, 0) gd.addNumericField(" add offset to Y coordinates", 0, 0) gd.addNumericField( " imaging stack # for excitation onset (0,1,..)", 0, 0) gd.addMessage('Press ENTER to save the coordinate file\n') gd.addMessage('Press ESC to restart\n') gd.showDialog() profileType = gd.getNextChoice() power = gd.getNextNumber() duration = gd.getNextNumber() prewait = gd.getNextNumber() zStart = gd.getNextNumber() zStep = gd.getNextNumber() r = gd.getNextNumber() Nturns = gd.getNextNumber() camTriggerEvery = gd.getNextNumber() xOffset = gd.getNextNumber() yOffset = gd.getNextNumber() tmIndex = gd.getNextNumber() if gd.wasCanceled(): IJ.setTool(Toolbar.RECTANGLE) return else: return r, power, profileType, duration, Nturns, camTriggerEvery, zStart, zStep, prewait, xOffset, yOffset, tmIndex
def getOptions(imp): gd = GenericDialog("Correct 2D/3D Drift Options") channels = [] for ch in range(1, imp.getNChannels()+1 ): channels.append(str(ch)) gd.addChoice("Channel for registration:", channels, channels[0]) gd.addCheckbox("Correct only x & y (for 3D data):", False) gd.addCheckbox("Multi_time_scale computation for enhanced detection of slow drifts?", False) gd.addCheckbox("Sub_pixel drift correction (possibly needed for slow drifts)?", False) gd.addCheckbox("Edge_enhance images for possibly improved drift detection?", False) gd.addNumericField("Only consider pixels with values larger than:", 0, 0) gd.addNumericField("Lowest z plane to take into account:", 1, 0) gd.addNumericField("Highest z plane to take into account:", imp.getNSlices(), 0) gd.addNumericField("Max_shift_x [pixels]:", 10, imp.getWidth()) gd.addNumericField("Max_shift_y [pixels]:", 10, imp.getHeight()) gd.addNumericField("Max_shift_z [pixels]:", 10, imp.getNSlices()) gd.addCheckbox("Use virtualstack for saving the results to disk to save RAM?", False) gd.addCheckbox("Only compute drift vectors?", False) gd.addMessage("If you put a ROI, drift will only be computed in this region;\n the ROI will be moved along with the drift to follow your structure of interest.") gd.showDialog() if gd.wasCanceled(): return options = {} options['channel'] = gd.getNextChoiceIndex() + 1 # zero-based options['correct_only_xy'] = gd.getNextBoolean() options['multi_time_scale'] = gd.getNextBoolean() options['subpixel'] = gd.getNextBoolean() options['process'] = gd.getNextBoolean() options['background'] = gd.getNextNumber() options['z_min'] = gd.getNextNumber() options['z_max'] = gd.getNextNumber() max_shifts = [0,0,0] max_shifts[0] = gd.getNextNumber() max_shifts[1] = gd.getNextNumber() max_shifts[2] = gd.getNextNumber() options['max_shifts'] = max_shifts options['virtual'] = gd.getNextBoolean() options['only_compute'] = gd.getNextBoolean() return options
def get_setup(): '''Returns two ImagePlus objects and a dictionary of properties to copy.''' dialog = GenericDialog('Copy Properties setup') dialog.addMessage('Select the source and target image and the properties to copy.') image_ids = WindowManager.getIDList() if not image_ids or len(image_ids) < 2: IJ.showMessage('Two or more images are necessary to use this plugin.') return [None]*3 image_titles = [WindowManager.getImage(id).getTitle() for id in image_ids] dialog.addChoice('Source', image_titles, image_titles[0]) dialog.addChoice('Target', image_titles, image_titles[1]) dialog.addCheckbox('Copy Calibration', True) dialog.addCheckbox('Copy Slice Labels', False) dialog.showDialog() if dialog.wasCanceled(): return [None]*3 source = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()]) target = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()]) choices = {'cal': dialog.getNextBoolean(), 'labels': dialog.getNextBoolean() } return source, target, choices
def getNames(): info = [] gd = GenericDialog("Naming options") gd.addChoice("How would you like to output your results?", ["default", "use information csv file"], "default") gd.showDialog() choice = gd.getNextChoice() log.write("Option: " + choice + "\n") if choice == "use information csv file": path = OpenDialog("Open the names csv file") log.write("File used: " + path.getPath() + "\n") with open(path.getPath()) as csvfile: reader = csv.DictReader(csvfile) for row in reader: info.append(row) return info
def make_directory(imgDir): """ Makes the necessary output directories or overwrites current ones. """ if not path.exists(imgDir) or not path.isdir(imgDir): print "Not a valid directory" exit(0) if not path.exists(imgDir+"/binary"): mkdir(imgDir+"/binary") else: gd = GenericDialog("Confirm Overwrite") choices = ["Yes", "No"] gd.addChoice("Overwrite \"binary\" folder?", choices, choices[0]) gd.showDialog() if gd.wasCanceled(): exit(0) choice = gd.getNextChoice() if choice == "No": exit(0) shutil.rmtree(imgDir+"/binary") mkdir(imgDir+"/binary") if not path.exists(imgDir+"/greyscale"): mkdir(imgDir+"/greyscale") else: gd = GenericDialog("Confirm Overwrite") choices = ["Yes", "No"] gd.addChoice("Overwrite \"greyscale\" folder?", choices, choices[0]) gd.showDialog() if gd.wasCanceled(): exit(0) choice = gd.getNextChoice() if choice == "No": exit(0) shutil.rmtree(imgDir+"/greyscale") mkdir(imgDir+"/greyscale")
def make_directory(imgDir): """ Makes the necessary output directories or overwrites current ones. """ if not path.exists(imgDir) or not path.isdir(imgDir): print "Not a valid directory" exit(0) if not path.exists(imgDir + "/binary"): mkdir(imgDir + "/binary") else: gd = GenericDialog("Confirm Overwrite") choices = ["Yes", "No"] gd.addChoice("Overwrite \"binary\" folder?", choices, choices[0]) gd.showDialog() if gd.wasCanceled(): exit(0) choice = gd.getNextChoice() if choice == "No": exit(0) shutil.rmtree(imgDir + "/binary") mkdir(imgDir + "/binary") if not path.exists(imgDir + "/greyscale"): mkdir(imgDir + "/greyscale") else: gd = GenericDialog("Confirm Overwrite") choices = ["Yes", "No"] gd.addChoice("Overwrite \"greyscale\" folder?", choices, choices[0]) gd.showDialog() if gd.wasCanceled(): exit(0) choice = gd.getNextChoice() if choice == "No": exit(0) shutil.rmtree(imgDir + "/greyscale") mkdir(imgDir + "/greyscale")
def setupDialog(): gd = GenericDialog("Toolbox options") gd.addMessage("Imagej toolbox, choose an image: ") # gd.addNumericField("Frame interval:", default_interval, 2) # show 2 decimals # gd.addCheckbox("Do you want to use a gliding window?", True) # gd.addCheckbox("Project hyperStack? (defaluts to projecting current channel only)", False) # gd.addStringField("time unit",default_timeunit, 3) # gd.addSlider("Start compacting at frame:", 1, imp.getNFrames(), 1) # gd.addSlider("Stop compacting at frame:", 1, imp.getNFrames(), imp.getNFrames()) # gd.addNumericField("Number of frames to project in to one:", 3, 0) # show 0 decimals gd.addChoice("Choose image:", image_titles, imp.getTitle()) gd.addChoice('Choose pipeline:', pipelines_as_strings, pipelines_as_strings[0]) gd.showDialog() if gd.wasCanceled(): IJ.log("User canceled dialog!") return return gd
def get_setup(): ''' Returns the drift correction mode and two image.''' options = drift.get_options() modes = drift.get_modes() dialog = GenericDialog('Jump-ratio setup') dialog.addMessage('Select the mode for drift correction\n' + 'and the images to process.') dialog.addChoice('Mode:', options, options[0]) image_ids = WindowManager.getIDList() if not image_ids or len(image_ids) < 2: return [None]*3 image_titles = [WindowManager.getImage(id).getTitle() for id in image_ids] dialog.addMessage('Post-edge is divided by the pre-edge.') dialog.addChoice('Pre-edge', image_titles, image_titles[0]) dialog.addChoice('Post-edge', image_titles, image_titles[1]) dialog.showDialog() if dialog.wasCanceled(): return [None]*3 mode = modes[dialog.getNextChoiceIndex()] img1 = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()]) img2 = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()]) return mode, img1, img2
def run(): types = ['oneDay','oneMouse','oneFile','oneMonth','OneFolder','mapManager'] gd = GenericDialog('Define Source Options') #gd.addMessage('Choose the Source type:') gd.addChoice('Source Type:',types,types[0]) gd.showDialog() if gd.wasCanceled(): bPrintLog('user cancel the plugin',1) return 0 else: srcType = gd.getNextChoiceIndex() #run one day if srcType == 0: dayFolder = DirectoryChooser('Please Choose A Directory Of .tif Files').getDirectory() if not os.path.isdir(dayFolder): bPrintLog('\nERROR: runOneDay() did not find folder: ' + dayFolder + '\n',0) return 0 overWriteDate(dayFolder) #run one mouse if srcType == 1: mouseFolder = DirectoryChooser('Please Choose A Mouse Directory Of .tif Files').getDirectory() if not mouseFolder: exit(1) overWriteMouse(mouseFolder) #run one file if srcType == 2: od = OpenDialog("Choose a convoluted tif file to overwrite", None) srcDirectory = od.getDirectory() srcFile = od.getFileName() if srcFile != None: fileFullPath = os.path.join(srcDirectory,srcFile) convert32to16(fileFullPath) #run one month if srcType == 3: monthFolder = DirectoryChooser('Please Choose A MONTH Directory Of .tif Files').getDirectory() if not os.path.isdir(monthFolder): bPrintLog('\nERROR: runOneMonth() did not find folder: ' + monthFolder + '\n',0) return 0 runOneMonth(monthFolder) #run one Folder if srcType == 4: srcFolder = DirectoryChooser('Please Choose A folder Of .tif Files').getDirectory() if not os.path.isdir(srcFolder): bPrintLog('\nERROR: runOneFolder() did not find folder: ' + srcFolder + '\n',0) return 0 runOneFolder(srcFolder) if srcType == 5: #align centain map's raw folder mapPath = 'G:/ZY/MapManager3' #mapNames = raw_input('type maps initials seperated with ,: ').split(',') #raw_input does not work here #mapNames = tuple(mapNames) mapNames = "F58,F59" #preset #get map names gd = GenericDialog('Choose maps for alignment') gd.addStringField("maps root path",mapPath,50) gd.addStringField("maps name initials sep = ','(empty for all)",mapNames,50) gd.showDialog() if gd.wasCanceled(): bPrintLog('user cancel the plugin',0) return 0 mapPath = gd.getNextString() mapNames = tuple(gd.getNextString().split(',')) mapFolders = [f for f in os.listdir(mapPath) if f.startswith(mapNames) and os.path.isdir(os.path.join(mapPath,f))] if len(mapFolders) == 0: bPrintLog('\nERROR: no map folder found',0) return 0 bPrintLog('Map Folder number: ' + str(len(mapFolders)),0) #put option here so we do not have to click for each folder sourceFolders= [mapPath + '/' + mapFolder + '/raw/raw_userRaw' for mapFolder in mapFolders] for srcFolder in sourceFolders: runOneFolder(srcFolder)
def run(): types = [ 'oneDay', 'oneMouse', 'oneFile', 'oneMonth', 'OneFolder', 'mapManager' ] gd = GenericDialog('Define Source Options') #gd.addMessage('Choose the Source type:') gd.addChoice('Source Type:', types, types[0]) gd.showDialog() if gd.wasCanceled(): bPrintLog('user cancel the plugin', 1) return 0 else: srcType = gd.getNextChoiceIndex() #run one day if srcType == 0: dayFolder = DirectoryChooser( 'Please Choose A Directory Of .tif Files').getDirectory() if not os.path.isdir(dayFolder): bPrintLog( '\nERROR: runOneDay() did not find folder: ' + dayFolder + '\n', 0) return 0 overWriteDate(dayFolder) #run one mouse if srcType == 1: mouseFolder = DirectoryChooser( 'Please Choose A Mouse Directory Of .tif Files').getDirectory( ) if not mouseFolder: exit(1) overWriteMouse(mouseFolder) #run one file if srcType == 2: od = OpenDialog("Choose a convoluted tif file to overwrite", None) srcDirectory = od.getDirectory() srcFile = od.getFileName() if srcFile != None: fileFullPath = os.path.join(srcDirectory, srcFile) convert32to16(fileFullPath) #run one month if srcType == 3: monthFolder = DirectoryChooser( 'Please Choose A MONTH Directory Of .tif Files').getDirectory( ) if not os.path.isdir(monthFolder): bPrintLog( '\nERROR: runOneMonth() did not find folder: ' + monthFolder + '\n', 0) return 0 runOneMonth(monthFolder) #run one Folder if srcType == 4: srcFolder = DirectoryChooser( 'Please Choose A folder Of .tif Files').getDirectory() if not os.path.isdir(srcFolder): bPrintLog( '\nERROR: runOneFolder() did not find folder: ' + srcFolder + '\n', 0) return 0 runOneFolder(srcFolder) if srcType == 5: #align centain map's raw folder mapPath = 'G:/ZY/MapManager3' #mapNames = raw_input('type maps initials seperated with ,: ').split(',') #raw_input does not work here #mapNames = tuple(mapNames) mapNames = "F58,F59" #preset #get map names gd = GenericDialog('Choose maps for alignment') gd.addStringField("maps root path", mapPath, 50) gd.addStringField("maps name initials sep = ','(empty for all)", mapNames, 50) gd.showDialog() if gd.wasCanceled(): bPrintLog('user cancel the plugin', 0) return 0 mapPath = gd.getNextString() mapNames = tuple(gd.getNextString().split(',')) mapFolders = [ f for f in os.listdir(mapPath) if f.startswith(mapNames) and os.path.isdir(os.path.join(mapPath, f)) ] if len(mapFolders) == 0: bPrintLog('\nERROR: no map folder found', 0) return 0 bPrintLog('Map Folder number: ' + str(len(mapFolders)), 0) #put option here so we do not have to click for each folder sourceFolders = [ mapPath + '/' + mapFolder + '/raw/raw_userRaw' for mapFolder in mapFolders ] for srcFolder in sourceFolders: runOneFolder(srcFolder)
def Options(sourceFolder): #globals global gFileType global gGetNumChanFromScanImage global gNumChannels global gDoAlign global gAlignThisChannel global gDoCrop global gCropLeft global gCropTop global gCropWidth global gCropHeight global gAlignOnMiddleSlice global gAlignOnThisSlice global gRemoveCalibration global gLinearShift global gSave8bit tifNames = [file.name for file in File(sourceFolder).listFiles(Filter())] lsmNames = [file.name for file in File(sourceFolder).listFiles(Filter_LSM())] numTifs = len(tifNames) numLSM = len(lsmNames) gd = GenericDialog('Align Batch 7 Options') #gd.addStringField('Command: ', '') gd.addMessage('Source Folder: ' + sourceFolder) gd.addMessage('Number of .tif files: ' + str(numTifs)) gd.addMessage('Number of .lsm files: ' + str(numLSM)) gd.addChoice('File Type', ['tif','lsm'], gFileType) #gd.setInsets(5,0,3) #0 gd.addCheckboxGroup(1, 1, ['Get Number Of Channels From ScanImage 3.x or 4.x header'], [gGetNumChanFromScanImage], ['Channels']) gd.addNumericField('Otherwise, Assume All Stacks Have This Number Of Channels: ', gNumChannels, 0) print gLinearShift #1 gd.addCheckboxGroup(1, 1, ['Remove Linear Calibration From ScanImage 4.x'], [gRemoveCalibration], ['ScanImage4']) gd.addNumericField('And offset (subtract) by this amount: ', gLinearShift, 0) gd.addMessage('20151110, this number = 2^15-512 = 32768-512 = 32256') #2 gd.addCheckboxGroup(1, 1, ['Crop All Images (pixels)'], [gDoCrop], ['Crop']) gd.addNumericField('Left', gCropLeft, 0) gd.addNumericField('Top', gCropTop, 0) gd.addNumericField('Width', gCropWidth, 0) gd.addNumericField('Height', gCropHeight, 0) #gd.setInsets(5,0,3) #3 gd.addCheckboxGroup(1, 1, ['Run MultiStackReg'], [gDoAlign], ['MultStackReg']) gd.addNumericField('If 2 Channels Then Align On This Channel', gAlignThisChannel, 0) #4 gd.addCheckboxGroup(1, 1, ['Start Alignment On Middle Slice'], [gAlignOnMiddleSlice], ['Align On Middle Slice']) gd.addNumericField('Otherwise, Start Alignment On This Slice', gAlignOnThisSlice, 0) #5 gd.addCheckboxGroup(1, 1, ['Save 8-bit'], [gSave8bit], ['Save 8-bit (at end)']) #gd.addCheckbox('Save 8-bit', gSave8bit) gd.showDialog() if gd.wasCanceled(): print 'Options Was Cancelled by user' return 0 else: print 'Reading values' gFileType = gd.getNextChoice() gNumChannels = int(gd.getNextNumber()) gLinearShift = int(gd.getNextNumber()) gCropLeft = int(gd.getNextNumber()) gCropTop = int(gd.getNextNumber()) gCropWidth = int(gd.getNextNumber()) gCropHeight = int(gd.getNextNumber()) gAlignThisChannel = int(gd.getNextNumber()) gAlignOnThisSlice = int(gd.getNextNumber()) checks = gd.getCheckboxes() checkIdx = 0 for check in checks: #print check.getState() if checkIdx==0: gGetNumChanFromScanImage = check.getState() if checkIdx==1: gRemoveCalibration = check.getState() if checkIdx==2: gDoCrop = check.getState() if checkIdx==3: gDoAlign = check.getState() if checkIdx==4: gAlignOnMiddleSlice = check.getState() if checkIdx==5: gSave8bit = check.getState() checkIdx += 1 # print to fiji console bPrintLog('These are your global options:', 0) bPrintLog('gFileType=' + gFileType, 1) bPrintLog('gGetNumChanFromScanImage=' + str(gGetNumChanFromScanImage), 1) bPrintLog('gNumChannels=' + str(gNumChannels), 1) bPrintLog('gRemoveCalibration=' + str(gRemoveCalibration), 1) bPrintLog('gLinearShift=' + str(gLinearShift), 1) bPrintLog('gDoCrop=' + str(gDoCrop), 1) bPrintLog('gDoAlign=' + str(gDoAlign), 1) bPrintLog('gAlignThisChannel=' + str(gAlignThisChannel), 1) bPrintLog('gSave8bit=' + str(gSave8bit), 1) return 1
from ij.process import ImageProcessor from ij.process import ImageConverter from ij.gui import WaitForUserDialog from ij.gui import GenericDialog from ij.plugin.frame import RoiManager from ij.plugin.filter import ParticleAnalyzer from ij.plugin import ChannelSplitter # Set Threshold mode thresholdMode = False gd = GenericDialog("Set Threshold Mode") gd.addChoice("Would you like to enable thresholding mode?", ["No, run the normal macro", "Yes, enable thresholding mode"], "No") gd.showDialog() if gd.getNextChoice() == "Yes, enable thresholding mode": thresholdMode = True gd = GenericDialog("Set Thresholds") gd.addStringField("Lower bound for Red", "90") gd.addStringField("Lower bound for Green", "90") gd.addStringField("Lower bound for Blue", "100") gd.showDialog() thresholds = {} thresholds["Red"] = int(gd.getNextString() ) thresholds["Green"] = int(gd.getNextString()
from ij.measure import ResultsTable from ij.gui import WaitForUserDialog from ij.plugin.filter import Analyzer from ij import ImagePlus from ij.plugin import ImageCalculator wList = WindowManager.getIDList() if (wList): theImage = IJ.getImage() titles = [] for i in range(len(wList)): imp = WindowManager.getImage(wList[i]) titles.append(imp.getTitle()) gd = GenericDialog("Pick images") gd.addChoice("Main channel:",titles,titles[0]) gd.addChoice("Subtracted channel:",titles,titles[1]) gd.showDialog() if (gd.wasCanceled()): quit() index1 = gd.getNextChoiceIndex() index2 = gd.getNextChoiceIndex() image1 = WindowManager.getImage(wList[index1]) image2 = WindowManager.getImage(wList[index2]) IJ.selectWindow(wList[index1]) rt = ResultsTable.getResultsTable() rt.reset() gd = WaitForUserDialog("Pick region with only bleedthrough")
'''Display help for any CMTK tool''' from ij.gui import GenericDialog from java.awt.event import ItemListener import cmtkgui import os class ToolListener(ItemListener): def itemStateChanged(self, isc): toolc=choicef.getSelectedItem() helptext=cmtkgui.run_tool_stdout(toolc,'--help') print helptext ta.setText(helptext) gd = GenericDialog('Help for CMTK Tool') tools=os.listdir(cmtkgui.bin_dir()) gd.addChoice('CMTK tool',tools,tools[0]) choicef=gd.getChoices().get(0) choicef.addItemListener(ToolListener()) gd.addTextAreas('',None,50,80) ta=gd.getTextArea1() ta.setEditable(False) gd.showDialog() # gd.addMessage('Currently installed CMTK version: '+cmtkgui.installed_version())
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))
def processDirectory(): # start logging IJ.log("\n______________________________\n\n\t\tOlympus DM correction\n\t\tVersion " + pluginVersion +"\n______________________________\n") # ask user for an input directory dc = DirectoryChooser("Choose folder containing Olympus (.oir) files") inputDir = dc.getDirectory() if inputDir is None: IJ.log("User canceled the dialog!\nImage processing canceled!\n") return IJ.log("\nInput directory: " + inputDir + "\n") oirFiles = [] for f in os.listdir(inputDir): if f.endswith(".oir"): oirFiles.append(f) if len(oirFiles) < 1: IJ.log("Input directory does not contain any Olympus (.oir) files.\nNo images to process.\n") return # find out how many channels are in first file (we will assume all files have same number of channels and were acquired using same DMs) reader = ImageReader() omeMeta = MetadataTools.createOMEXMLMetadata() reader.setMetadataStore(omeMeta) reader.setId(inputDir + oirFiles[0]) numChannels = reader.getSizeC() # ask user to identify dichroic mirror used for each channel gdDM = GenericDialog("Dichroic mirrors") DMs = ["DM1", "DM2", "DM3", "DM4", "DM5"] for i in range(numChannels): gdDM.addChoice("Channel " + str(i+1), DMs, DMs[0]) gdDM.addCheckbox("Merge channels", False) gdDM.showDialog() if gdDM.wasCanceled(): IJ.log("User canceled the dialog!\nImage processing canceled!\n") return dichroics = [] for i in range(numChannels): dichroics.append(gdDM.getNextChoice()) merge = gdDM.getNextBoolean() IJ.log("User selected dichroic mirrors") for i in range(numChannels): IJ.log("\t\tChannel " + str(i+1) + ": " + dichroics[i]) IJ.log("\n") if merge: channels = [] chDict = {} for i in range(numChannels): chName = "Channel"+str(i+1) channels.append(chName) chDict[chName] = i channels.append("NONE") colourChoices = ["red", "green", "blue", "gray", "cyan", "magenta", "yellow"] gdMerge = GenericDialog("Merge channels") for c in colourChoices: gdMerge.addChoice(c + ":", channels, channels[numChannels]) gdMerge.showDialog() if gdMerge.wasCanceled(): IJ.log("User canceled the dialog!\nImage processing canceled!\n") return IJ.log("User selected channel colours") usersMergeList = [] for i in range(len(colourChoices)): ch = gdMerge.getNextChoice() if ch == "NONE": usersMergeList.append(None) else: usersMergeList.append(chDict[ch]) IJ.log("\t\t" + colourChoices[i] + ": " + ch) IJ.log("\n\n") # ask user for an output directory dc = DirectoryChooser("Choose folder for output") outputDir = dc.getDirectory() if outputDir is None: IJ.log("User canceled the dialog!\nImage processing canceled!\n") return counter = 0 totalFiles = len(oirFiles) for o in oirFiles: counter +=1 IJ.log("Processing file " + str(counter) + " of " + str(totalFiles) + "\n") IJ.log("File path: " + inputDir + o) if merge: ml = usersMergeList[:] else: ml = None processFile(o, inputDir, outputDir, dichroics, ml) IJ.log("\n--------------------------\n")
def run(): types = ['oneDay','oneFolder','oneFile','mapmaneger','test'] gd = GenericDialog('Define Source Options') #gd.addMessage('Choose the Source type:') gd.addChoice('Source Type:',types,types[0]) gd.showDialog() if gd.wasCanceled(): print 'user cancel the plugin' return 0 else: srcType = gd.getNextChoiceIndex() #run one day if srcType == 0: dayFolder = DirectoryChooser('Please Choose A Directory Of .tif Files').getDirectory() if not os.path.isdir(dayFolder): bab.bPrintLog('\nERROR: runOneDay() did not find folder: ' + dayFolder + '\n',0) return 0 dirNames = [file for file in os.listdir(dayFolder) if os.path.isdir(os.path.join(dayFolder,file))] numDirs = len(dirNames) bab.bPrintLog('dayFolder is:' + dayFolder,0) bab.bPrintLog('Number of subFolders: ' + str(numDirs),1) #put option here so we do not have to click for each folder if bab.Options(dayFolder + dirNames[0] + '/'): for dirName in dirNames: #sourceFolder = os.path.join(dayFolder, dirName) # did not add '/' to the end sourceFolder = dayFolder + '/' + dirName + '/' bab.runOneFolder(sourceFolder) #run one folder if srcType == 1: sourceFolder = DirectoryChooser('Please Choose A Directory Of .tif Files').getDirectory() if not sourceFolder: exit(1) if bab.Options(sourceFolder): bab.runOneFolder(sourceFolder) #run one file if srcType == 2: od = OpenDialog("Choose image file", None) srcDirectory = od.getDirectory() srcFile = od.getFileName() if srcFile != None and bab.Options(srcDirectory): bab.runOneFile(srcDirectory + srcFile) if srcType == 3: #align centain map's raw folder mapPath = 'G:/ZY/MapManager3' #mapNames = raw_input('type maps initials seperated with ,: ').split(',') #raw_input does not work here #mapNames = tuple(mapNames) mapNames = "F58,F59" #preset #get map names gd = GenericDialog('Choose maps for alignment') gd.addStringField("maps root path",mapPath,50) gd.addStringField("maps name initials sep = ','",mapNames,50) gd.showDialog() if gd.wasCanceled(): bab.bPrintLog('user cancel the plugin',0) return 0 mapPath = gd.getNextString() mapNames = tuple(gd.getNextString().split(',')) mapFolders = [f for f in os.listdir(mapPath) if f.startswith(mapNames) and os.path.isdir(os.path.join(mapPath,f))] if len(mapFolders) == 0: bab.bPrintLog('\nERROR: no map folder found',0) return 0 bab.bPrintLog('Map Folder number: ' + str(len(mapFolders)),0) #put option here so we do not have to click for each folder sourceFolders= [mapPath + '/' + mapFolder + '/raw/' for mapFolder in mapFolders] if bab.Options(sourceFolders[0]): for sourceFolder in sourceFolders: bab.runOneFolder(sourceFolder) if srcType == 4: #for test gd = GenericDialog('Choose maps') gd.addStringField('maps name initials','F58,F59') gd.showDialog() maps = gd.getNextString().split(',') maps = tuple(maps) bab.bPrintLog(maps[0],0)
def uScopeCalDialog(cal): ''' Pop up a dialog asking user to edit line settings etc. CalIdx, SetGlobalScale, AddScaleBar = uScopeCalDialog(cal) `cal` should be the object containing `names`, `cals`, `units` attributes as set in the "user_settings.py" file. `CalIdx` is the list index to the chosen calibration. Eg., if the options were ['5x', '10x', '20x'] and the user chose '10x', then CalIdx = 1 Returns `None` if the user cancelled the dialog. `SetGlobalScale` is a boolean (True/False) from a checkbox option, if the user wants this calibration set 'globally' to all open images. `AddScaleBar` is also a boolean (True/False), for a checkbox option, if user would like to run "Scale Bar..." afterwards. ''' # The following inspired heavily by Correct_3D_drift.py: #print "uScopeCalDialog():" #print cal.names, [str(x) for x in cal.cals] gd = GenericDialog("Microscope Calibrations") gd.addMessage("Choose the calibration to load:") # generate text to display in list: # Radio Buttons: CalStr = [] CalType_IsFunc = [] for ii, name in enumerate(cal.names): if MC_DEBUG: print("item #%i: name=" % (ii), name, "\n\t type=", type(name)) if isinstance(name, basestring): '''It's just a regular calibration setting''' CalStr.append(name + " (%s" % cal.cals[ii] + " pixels/%s)" % cal.units[ii]) else: ''' Assume we'll be loading a custom function/class ''' CalStr.append( name.name) # get the name from the Class' .name attribute #end if(str) #end for(cal.names) '''if > 20 cals, use dropdown list, otherwise use radio buttons''' if len(cal.names) > 20: Radio = False # Drop-Down list: gd.addChoice(" Calibration:", CalStr, CalStr[0]) # default = 1st (#0) else: Radio = True gd.addRadioButtonGroup(" Calibration:", CalStr, len(CalStr), 1, CalStr[0]) #addRadioButtonGroup(label, [String items], rows, columns, String:defaultItem) #end if(cal>20) gd.addCheckbox("Apply Scale to all open images?", False) gd.addCheckbox("Add Scale Bar to this image?", False) gd.addMessage( "These calibrations can be altered by editing the file: \nFiji.app/plugins/Scripts/Plugins/Analyze/...\n\tMicroscope Measurement Tools/...\n\tMicroscope_Calibrations_user_settings.py" ) gd.showDialog() if gd.wasCanceled(): return None, None, None # return None's if user cancels if Radio: ChosenCal = gd.getNextRadioButton() # Find the index to the chosen radio button w/ [list].index(): CalIdx = CalStr.index(ChosenCal) else: ChosenCal = gd.getNextChoiceIndex() CalIdx = ChosenCal # the index to the choice SetGlobalScale = gd.getNextBoolean() AddScaleBar = gd.getNextBoolean() #if MC_DEBUG: print( ChosenCal,CalIdx, SetGlobalScale ) #if MC_DEBUG: print( "end uScopeCalDialog()." ) return CalIdx, SetGlobalScale, AddScaleBar
def uScopeCalDialog(cal): ''' Pop up a dialog asking user to choose from the calibration names etc. CalIdx, SetGlobalScale, AddScaleBar = uScopeCalDialog(cal) `cal` should be the object containing `names`, `cals`, `units` attributes as set in the "user_settings.py" file. `CalIdx` is the list index to the chosen calibration. Eg., if the options were ['5x', '10x', '20x'] and the user chose '10x', then CalIdx = 1 Returns `None` if the user cancelled the dialog. `SetGlobalScale` is a boolean (True/False) from a checkbox option, if the user wants this calibration set 'globally' to all open images. `AddScaleBar` is also a boolean (True/False), for a checkbox option, if user would like to run "Scale Bar..." afterwards. ''' # The following inspired heavily by Correct_3D_drift.py: #print "uScopeCalDialog():" #print cal.names, [str(x) for x in cal.cals] gd = GenericDialog("Microscope Calibrations") gd.addMessage("Choose the calibration to load:") # generate text to display in list: # Radio Buttons: CalStr = [] CalType_IsFunc = [] for ii, name in enumerate(cal.names): if mc_DEBUG: print( "item #%i: name=" % (ii), name, "\n\t type=", type(name) ) if isinstance(name, basestring): '''It's just a regular calibration setting''' CalStr.append( name + " (%s"%cal.cals[ii] + " pixels/%s)"%cal.units[ii] ) else: ''' Assume we'll be loading a custom function/class ''' CalStr.append( name.name ) # get the name from the Class' .name attribute #end if(str) #end for(cal.names) '''if > 20 cals, use dropdown list, otherwise use radio buttons''' if len(cal.names) > 20: Radio=False # Drop-Down list: gd.addChoice(" Calibration:", CalStr, CalStr[0] ) # default = 1st (#0) else: Radio=True gd.addRadioButtonGroup(" Calibration:", CalStr, len(CalStr), 1, CalStr[0]) #addRadioButtonGroup(label, [String items], rows, columns, String:defaultItem) #end if(cal>20) gd.addCheckbox("Apply Scale to all open images?", False) gd.addCheckbox("Add Scale Bar to this image?", False) gd.addMessage("These calibrations can be altered by editing the file: \nFiji.app/plugins/Scripts/Plugins/Analyze/...\n\tMicroscope Measurement Tools/...\n\tMicroscope_Calibrations_user_settings.py") gd.showDialog() if gd.wasCanceled(): return None, None, None # return None's if user cancels if Radio: ChosenCal = gd.getNextRadioButton() # Find the index to the chosen radio button w/ [list].index(): CalIdx = CalStr.index( ChosenCal ) else: ChosenCal = gd.getNextChoiceIndex() CalIdx = ChosenCal # the index to the choice SetGlobalScale = gd.getNextBoolean() AddScaleBar = gd.getNextBoolean() #if mc_DEBUG: print( ChosenCal,CalIdx, SetGlobalScale ) #if mc_DEBUG: print( "end uScopeCalDialog()." ) return CalIdx, SetGlobalScale, AddScaleBar
from ij import IJ from ij.gui import GenericDialog from ij.plugin import ChannelSplitter from ij.plugin import RGBStackMerge from ij.plugin import ImageCalculator from ij import WindowManager theImage = IJ.getImage() gd = GenericDialog("Options...") channelText = [("Channel " + str(ch+1)) for ch in range(theImage.getNChannels())] gd.addChoice("Amplified_channel",channelText,channelText[0]) gd.addChoice("Reference_channel",channelText,channelText[-1]) gd.addNumericField("Amplifying_ratio",1,0) gd.addCheckbox("Remove_bleedthrough",True) gd.addCheckbox("Correct_for_refraction",True) gd.showDialog() if gd.wasOKed(): amplifyChannel = gd.getNextChoiceIndex() + 1 refChannel = gd.getNextChoiceIndex() + 1 ampFactor = gd.getNextNumber() doRemoveBleedthrough = gd.getNextBoolean() doCorrectRefraction = gd.getNextBoolean() chImages = ChannelSplitter.split(theImage) ## After this step, the image to operate on is "nextStepImage" if doRemoveBleedthrough: params = ("bleeding_channel=" + str(refChannel) + " bloodied_channel=" + str(amplifyChannel) + " " + "allowable_saturation_percent=1.0 rsquare_threshold=0.50") IJ.run("Remove Bleedthrough (automatic)", params) unbledImage = WindowManager.getImage("Corrected_ch" + str(amplifyChannel)) mergingImages = [unbledImage,chImages[refChannel-1].duplicate()]
imp.close() print(xsize,ysize) for im in stitchedFiles: if not "hoechst" in im.lower(): IJ.open(inputDir1+im) imp = IJ.getImage() imp.setTitle(im.split('_')[0]) IJ.run("Images to Stack", "name=Stack title=[] use") imp = IJ.getImage() #IJ.run("Multiply...", "value=2.2") IJ.beep() gd = GenericDialog("Clockwise Rotation?") gd.addChoice("How Many Degrees",["0","90","180",'270'],"0") gd.showDialog() rotation = gd.getChoices().get(0).getSelectedItem() #in while loop while True: IJ.run("Stack to Images") IJ.run("Images to Stack", "name=Stack title=[] use") imp = IJ.getImage() myWait = ij.gui.WaitForUserDialog('Select Region to Load Full Res') myWait.show() region=IJ.getString("What to call region?", "") print(region) width=imp.getWidth() height=imp.getHeight()
def run(title): gd = GenericDialog("Record Window") gd.addMessage("Maximum number of frames to record.\nZero means infinite, interrupt with ESC key.") gd.addNumericField("Max. frames:", 50, 0) gd.addNumericField("Milisecond interval:", 300, 0) gd.addSlider("Start in (seconds):", 0, 20, 5) frames = [] titles = [] for f in Frame.getFrames(): if f.isEnabled() and f.isVisible(): frames.append(f) titles.append(f.getTitle()) gd.addChoice("Window:", titles, titles[0]) gd.addCheckbox("To file", False) gd.showDialog() if gd.wasCanceled(): return n_frames = int(gd.getNextNumber()) interval = gd.getNextNumber() / 1000.0 # in seconds frame = frames[gd.getNextChoiceIndex()] delay = int(gd.getNextNumber()) tofile = gd.getNextBoolean() dir = None if tofile: dc = DirectoryChooser("Directory to store image frames") dir = dc.getDirectory() if dir is None: return # dialog canceled snaps = [] borders = None executors = Executors.newFixedThreadPool(1) try: while delay > 0: IJ.showStatus("Starting in " + str(delay) + "s.") time.sleep(1) # one second delay -= 1 IJ.showStatus("Capturing frame borders...") bounds = frame.getBounds() robot = Robot() frame.toFront() time.sleep(0.5) # half a second borders = robot.createScreenCapture(bounds) IJ.showStatus("Recording " + frame.getTitle()) # Set box to the inside borders of the frame insets = frame.getInsets() box = bounds.clone() box.x = insets.left box.y = insets.top box.width -= insets.left + insets.right box.height -= insets.top + insets.bottom start = System.currentTimeMillis() / 1000.0 # in seconds last = start intervals = [] real_interval = 0 i = 1 fus = None if tofile: fus = [] # 0 n_frames means continuous acquisition while 0 == n_frames or (len(snaps) < n_frames and last - start < n_frames * interval): now = System.currentTimeMillis() / 1000.0 # in seconds real_interval = now - last if real_interval >= interval: last = now img = snapshot(frame, box) if tofile: fus.append(executors.submit(Saver(i, dir, bounds, borders, img, insets))) # will flush img i += 1 else: snaps.append(img) intervals.append(real_interval) else: time.sleep(interval / 5) # interrupt capturing: if IJ.escapePressed(): IJ.showStatus("Recording user-interrupted") break # debug: # print "insets:", insets # print "bounds:", bounds # print "box:", box # print "snap dimensions:", snaps[0].getWidth(), snaps[0].getHeight() # Create stack stack = None if tofile: for fu in snaps: fu.get() # wait on all stack = VirtualStack(bounds.width, bounds.height, None, dir) files = File(dir).list(TifFilter()) Arrays.sort(files) for f in files: stack.addSlice(f) else: stack = ImageStack(bounds.width, bounds.height, None) t = 0 for snap, real_interval in zip(snaps, intervals): bi = BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_RGB) g = bi.createGraphics() g.drawImage(borders, 0, 0, None) g.drawImage(snap, insets.left, insets.top, None) stack.addSlice(str(IJ.d2s(t, 3)), ImagePlus("", bi).getProcessor()) t += real_interval snap.flush() bi.flush() borders.flush() ImagePlus(frame.getTitle() + " recording", stack).show() IJ.showStatus("Done recording " + frame.getTitle()) except Exception, e: print "Some error ocurred:" print e.printStackTrace() IJ.showStatus("") if borders is not None: borders.flush() for snap in snaps: snap.flush()
computedImage.close() 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
inputDirectory = dc.getDirectory() dc = DirectoryChooser("Select an output directory") outputDirectory = dc.getDirectory() for image in os.listdir(inputDirectory): print(image) if "stack" in image: imp = IJ.openImage(inputDirectory + "/" + image) imp2 = IJ.openImage(inputDirectory + "/" + image.replace("stack", "montage")) imp.show() imp2.show() gd = GenericDialog("?") gd.addChoice("Would you like to adjust this one?", ["No", "Yes"], "No") gd.showDialog() if gd.getNextChoice() == "Yes": imp2.close() IJ.run("Brightness/Contrast...") WaitForUserDialog("Title", "Adjust intensities").show() IJ.run("Stack to Images", "") IJ.run(imp, "Merge Channels...", "c2=Green c3=Blue c6=Magenta c7=Yellow create keep") imp = WindowManager.getCurrentImage() IJ.run(imp, "RGB Color", "") IJ.run(imp, "Images to Stack", "name=Stack title=[] use") #WaitForUserDialog("Title", "Now you should have a stack check it out ").show() imp = WindowManager.getCurrentImage() # the Stack imp.show()
def dialog(self): """ Open the classifier dialog window and return the paramters chosen. """ # determine how many images are currently open image_count = WindowManager.getImageCount() image_titles = list(WindowManager.getImageTitles()) image_titles.append("None") # now open a dialog to let the user set options path_listener = SetPathListener(self.path) path_button = TrimmedButton("Output directory",0) path_button.addActionListener(path_listener) dlg = GenericDialog("Create classifier data (v"+__version__+")") dlg.addMessage("Session ID: "+ str(self.session_id)) dlg.addMessage("") dlg.addMessage("Select the ROI you want to save") dlg.addNumericField("Window size (pixels): ", self.window_size, 0) dlg.addChoice("Class label: ", DEFAULT_CLASSES+['Other...'], DEFAULT_CLASSES[0]) dlg.addStringField("Class label (if other): ", "") dlg.addChoice("Image file #1 (BF):",image_titles,"None") dlg.addChoice("Image file #2 (GFP):",image_titles,"None") dlg.addChoice("Image file #3 (RFP):",image_titles,"None") dlg.addChoice("Mask file:",image_titles,"None") dlg.addCheckbox("Rename ROIs", True) dlg.addCheckbox("Exclude edges", True) dlg.addCheckbox("Save ROI zip", True) dlg.addCheckbox("Save classifier details", True) dlg.add(path_button) dlg.showDialog() # handle the cancelled dialog box if dlg.wasCanceled(): return None label_option = dlg.getNextChoice() if label_option == 'Other...': label = dlg.getNextString() else: label = label_option # get the root path from the path listener root_path = path_listener.path if not os.path.isdir(root_path): w_dlg = GenericDialog("Warning") w_dlg.addMessage("Root path does not exist!!") w_dlg.showDialog() return None # try to make the directory for the label if it does not exist label_path = os.path.join(root_path, label) check_and_makedir(label_path) # get the options dialog_options = {'window_size': dlg.getNextNumber(), 'label': label, 'BF': dlg.getNextChoice(), 'GFP': dlg.getNextChoice(), 'RFP': dlg.getNextChoice(), 'mask': dlg.getNextChoice(), 'rename': dlg.getNextBoolean(), 'edges': dlg.getNextBoolean(), 'zip': dlg.getNextBoolean(), 'save': dlg.getNextBoolean(), 'path': label_path} # check that we actually selected an image file if all([dialog_options[d] == "None" for d in ['BF','GFP','RFP']]): w_dlg = GenericDialog("Warning") w_dlg.addMessage("You must select an image stream.") w_dlg.showDialog() return None # grab the contents and return these as a dictionary return dialog_options