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.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 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
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 run(): srcDir = IJ.getDirectory("Input_directory") if not srcDir: return dstDir = IJ.getDirectory("Output_directory") if not dstDir: return gd = GenericDialog("Process Folder") gd.addStringField("File_extension", ".tif") gd.addStringField("File_name_contains", "") gd.addCheckbox("Keep directory structure when saving", True) gd.addCheckbox("Show tracks", True) gd.showDialog() if gd.wasCanceled(): return ext = gd.getNextString() containString = gd.getNextString() keepDirectories = gd.getNextBoolean() showtracks = gd.getNextBoolean() for root, directories, filenames in os.walk(srcDir): for filename in filenames: # Check for file extension if not filename.endswith(ext): continue # Check for file name pattern if containString not in filename: continue process(srcDir, dstDir, root, filename, keepDirectories)
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 getOptions(): gd = GenericDialog("Options") gd.addCheckbox("Process_Right_Camera?", True) gd.addCheckbox("Process_Left_Camera?", True) gd.addNumericField("CamRScale: ", 214, 0) gd.addNumericField("CamLScale: ", 202, 0) gd.addNumericField("BackgroundWindowStart: ", 0, 0) gd.addNumericField("BackgroundWindowEnd: ", 600, 0) gd.addNumericField("GridSize: ", 10000, 0) gd.addNumericField("TranslateR: ", 0, 0) gd.addNumericField("TranslateL: ", 0, 0) gd.showDialog() # if gd.wasCanceled(): print "User canceled dialog!" return # Read out the options runCamR = gd.getNextBoolean() runCamL = gd.getNextBoolean() CamRScale = gd.getNextNumber() CamLScale = gd.getNextNumber() BackgroundWindowStart = gd.getNextNumber() BackgroundWindowEnd = gd.getNextNumber() GridSize = gd.getNextNumber() TranslateR = gd.getNextNumber() TranslateL = gd.getNextNumber() return runCamR, runCamL, CamRScale, CamLScale, BackgroundWindowStart, BackgroundWindowEnd, GridSize, TranslateR, TranslateL # a tuple with the parameters
def get_options(): """ Get user options. """ gd = GenericDialog("Options") gd.addCheckbox("3x3 boundary region", True) gd.addCheckbox("5x5 boundary region", True) # change the multiple of the standard deviation that is used # as a cutoff for the subtraction gd.addNumericField("N * sigma cutoff", 3.00, 2) # 2 decimals gd.showDialog() # check if user canceled operation if gd.wasCanceled(): return # pull options close = gd.getNextBoolean() far = gd.getNextBoolean() cutoff = gd.getNextNumber() return close, far, cutoff
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 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 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 get_opts(): gd = GenericDialog("setup plugin") #channels = map(lambda x: str(x), range(1,imp.getNChannels()+1)) channels = ['1','2','3']; modes = ['batch mode', 'manual'] gd.addChoice("processing mode",modes,modes[1]) gd.addChoice("choose channel for pre-registration: ", channels, channels[0]) gd.addChoice("choose channel for registration: ", channels, channels[2]) gd.addChoice("channel for cell detection: ", channels, channels[1]) gd.addChoice("channel for osteoblast detection: ", channels, channels[2]) gd.addChoice("channel for vasculature detection: ", channels, channels[0]) # gd.addNumericField("quantile for cell segmentation", 0.9995, 36) gd.addNumericField("rough cell size in microns", 15., 2) # gd.addSlider("minimal z depth (voxels) for detected cells", 1, imp.getNSlices()+1, 8) gd.addSlider("minimal z depth (voxels) for detected cells", 1,36, 5) gd.addSlider("minimal z depth (voxels) for detected cells", 1,36, 25) gd.addCheckbox("delete black frames (recommended)", True) gd.addChoice("channel to estimate black frames: ", channels, channels[2]) gd.addCheckbox("rough registration of time series", True) gd.addCheckbox("descriptor-based registration of time series", True) gd.addCheckbox("detect cells", False) gd.addCheckbox("export osteoblast structures", False) gd.addCheckbox("export vasculature structures", False) gd.addCheckbox("save registered movie", True) gd.addCheckbox("delete temporary files", True) #gd.addCheckbox("show 3d vis", False) gd.showDialog() proc_mode = gd.getNextChoice() ch_pre = gd.getNextChoice() reg = gd.getNextChoice() cc = gd.getNextChoice() ost_ch = gd.getNextChoice() vasc_ch = gd.getNextChoice() #quantile = gd.getNextNumber() size = gd.getNextNumber() minz = gd.getNextNumber() zmax = gd.getNextNumber() del_black = gd.getNextBoolean(); black_ch = gd.getNextChoice() preregflag = gd.getNextBoolean(); regflag = gd.getNextBoolean() detect_cells = gd.getNextBoolean() struct_exp = gd.getNextBoolean() vasc_exp = gd.getNextBoolean() save_res = gd.getNextBoolean() del_tmp = gd.getNextBoolean() #vis = gd.getNextBoolean() return proc_mode, ch_pre, reg, cc, ost_ch, vasc_ch, size, minz, zmax, del_black, black_ch, preregflag, regflag, detect_cells, struct_exp, vasc_exp, save_res, del_tmp
def optionsDialog(): gd = GenericDialog('bPrairie2tif options') # label, value, digits gd.addNumericField('Median Filter Pixel Size (0 for no filtering)', globalOptions['medianFilter'], 0) gd.addCheckbox('Convert to 8 bit', globalOptions['convertToEightBit']) gd.showDialog() if gd.wasCanceled(): return None globalOptions['medianFilter'] = gd.getNextNumber() globalOptions['convertToEightBit'] = gd.getNextBoolean() return 1
def getOptions(): global numberOfChannels global replaceExisting gd = GenericDialog("Options") gd.addNumericField("Number of channel", 2, 0) # show 0 decimals gd.addCheckbox("Replace Destination .tif files", 0) gd.addHelp("http://robertcudmore.org/software_index.html") gd.showDialog() if gd.wasCanceled(): print "User cancelled dialog." return -1 #read out options numberOfChannels = gd.getNextNumber() replaceExisting = gd.getNextBoolean() return 1 #int(numberOfChannels)
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 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 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
gd.addCheckbox("ALLOW_TRACK_SPLITTING", True) gd.addNumericField("SPLITTING_MAX_DISTANCE (pixel)", 20, 1) gd.addCheckbox("ALLOW_TRACK_MERGING", False) gd.addNumericField("MERGING_MAX_DISTANCE (pixel)", 20, 1) gd.addStringField("File_extension", ".tif") gd.addStringField("File_name_contains", "") gd.addCheckbox("Keep directory structure when saving", True) gd.addCheckbox("Show tracks", False) gd.showDialog() Pixel_calibration = gd.getNextNumber() Time_interval = gd.getNextNumber() LINKING_MAX_DISTANCE = gd.getNextNumber() GAP_CLOSING_MAX_DISTANCE = gd.getNextNumber() MAX_FRAME_GAP = int(gd.getNextNumber()) ALLOW_TRACK_SPLITTING = gd.getNextBoolean() SPLITTING_MAX_DISTANCE = gd.getNextNumber() ALLOW_TRACK_MERGING = gd.getNextBoolean() MERGING_MAX_DISTANCE = gd.getNextNumber() ext = gd.getNextString() containString = gd.getNextString() keepDirectories = gd.getNextBoolean() showtracks = gd.getNextBoolean() #print(LINKING_MAX_DISTANCE) #print(ALLOW_TRACK_SPLITTING) #print(SPLITTING_MAX_DISTANCE) #print(ALLOW_TRACK_MERGING) #print(MERGING_MAX_DISTANCE) #print(LINKING_MAX_DISTANCE) #print(ext)
dialog = GenericDialog( "Overlapping thickness estimation" ) dialog.addStringField( "Root directory for storing results", root ) dialog.addCheckbox( "Render matrix to image at each iteration.", False ) dialog.addNumericField( "Start.", 0, 0 ) dialog.addNumericField( "Stop.", height, 0 ) dialog.addNumericField( "Interval size.", 1000, 0 ) dialog.addNumericField( "Overlap.", imgSource.getWidth()/2, 0 ) dialog.addNumericField( "Range.", c, 0 ) dialog.showDialog() if dialog.wasCanceled(): raise Exception( "dialog was canceled" ) root = dialog.getNextString() doRender = dialog.getNextBoolean() start = dialog.getNextNumber() stop = dialog.getNextNumber() interval = dialog.getNextNumber() overlap = dialog.getNextNumber() c = dialog.getNextNumber() step = interval - overlap ImageConverter( imgSource ).convertToGray32() stat = FloatStatistics( imgSource.getProcessor() ) normalizeBy = stat.max imgSource.getProcessor().multiply( 1.0 / normalizeBy ) nThreads = 1
import glob dirChooser = DirectoryChooser("Choose directory of images to normalize...") dirPath = dirChooser.getDirectory() scaleXs = [] if dirPath is not None: if not os.path.exists(dirPath + "resized"): os.mkdir(dirPath + "resized") gd = GenericDialog("Settings...") gd.addNumericField("Final scale factor:",0.5,2) gd.addCheckbox("Convert multichannel to RGB:",True) gd.showDialog() if (gd.wasOKed()): common_scale = gd.getNextNumber() convert_to_rgb = gd.getNextBoolean() filecollection = glob.glob(os.path.join(dirPath, '*.tif')) if (len(filecollection) > 0): for path in filecollection: theImage = IJ.openImage(path) calibration = theImage.getCalibration() scaleXs.append(calibration.pixelWidth) theImage.close() lc_scale = max(scaleXs) print lc_scale for path in filecollection: theImage = IJ.openImage(path) bname1 = os.path.basename(path) bname2 = os.path.splitext(bname1)[0] this_cal = theImage.getCalibration() scale_factor = (this_cal.pixelWidth / lc_scale) * common_scale
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()
gd = GenericDialog("Set ToTiff Options") gd.addStringField("File extension to be processed", ".nd2") gd.addRadioButtonGroup("Output", outDirChoices, 3, 1, outDirChoices[0]) gd.addRadioButtonGroup("Overwrite", overwriteChoices, 2, 1, overwriteChoices[0]) gd.addRadioButtonGroup("Save channels in different subfolders", channelSubfolderChoices, 1, 1, channelSubfolderChoices[0]) gd.addCheckboxGroup(2, 1, mipChoices, [False, False], ["Do you want maximum intensity projections of your images?"]) gd.showDialog() if gd.wasCanceled(): exit() fileExt = gd.getNextString() outDirPref = gd.getNextRadioButton() overwritePref = gd.getNextRadioButton() channelSubfolderPref = gd.getNextRadioButton() mipPrefTIFF = gd.getNextBoolean() mipPrefJPG = gd.getNextBoolean() if not fileExt.startswith('.'): fileExt = '.' + fileExt inDir = IJ.getDirectory("Choose Directory Containing Input Files") if inDir is None: exit('No input directory selected!') if outDirPref == outDirChoices[2]: outDir = inDir else: outDir = IJ.getDirectory("Choose Directory For Output") if outDir is None: exit('No output directory selected!')
from ij.process import LUT from ij.process import StackConverter from java.awt import Color from ij.gui import GenericDialog dc = DirectoryChooser("Select folder to operate on...") dirPath = dc.getDirectory() if dirPath is not None: dc2 = DirectoryChooser("Select output directory...") outPath = dc2.getDirectory() if outPath is not None: gd = GenericDialog("Options...") gd.addCheckbox("Recolor_images",True) gd.showDialog() if (gd.wasOKed()): doRecolor = gd.getNextBoolean() for f in os.listdir(dirPath): if f.endswith(".tif") or f.endswith(".tiff"): theImage = IJ.openImage(dirPath+f) IJ.log("Loaded " + f) palette = [Color.GREEN,Color.RED,Color.BLUE] if (theImage.getNChannels() < 4): if doRecolor: for i in range(theImage.getNChannels()): theImage.setChannelLut(LUT.createLutFromColor(palette[i]),i+1) try: sc = StackConverter(theImage) sc.convertToRGB() IJ.saveAsTiff(theImage,outPath+os.path.splitext(f)[0]+"_rgb.tif") IJ.log("Completed " + f)
params = "open=["+ imgDir +"tile_"+str(tiles[0])+".ome.tif] color_mode=Default view=Hyperstack stack_order=XYCZT" IJ.run("Bio-Formats Importer", params); tileImage = WindowManager.getImage("tile_"+str(tiles[0])+".ome.tif") tileImage.setSlice(int(tileImage.getNSlices()/2)) else: ind = 1 tileDiskSize = os.path.getsize(imgDir+"tile_"+str(tiles[0])+".ome.tif") totalDiskSize = tileDiskSize * len(tiles) totalDiskSizeMB = totalDiskSize / 1048576 sizeGD = GenericDialog("Warning") sizeGD.addMessage("Memory used by selected tiles is " + str(totalDiskSizeMB) + "MB. Continue?") sizeGD.addCheckbox("Compute overlap",False) 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
def open_Octopus_file(): # set up a file info structure fi = FileInfo() fi.fileFormat = fi.RAW fi.fileType=FileInfo.GRAY16_UNSIGNED fi.intelByteOrder = True fi.nImages = 1 op = OpenDialog("Choose Octopus .dth file...", "") if not op.getDirectory(): return False # get the file extension file_extension = re.search('(\.[a-z][a-z][a-z])', op.getFileName()).group(1) if file_extension != ".dth": dlg = GenericDialog("Warning") dlg.addMessage("Please select an octopus .dth file") dlg.showDialog() return False # now strip the filename into a stem and index file_parse = re.match('([a-zA-z0-9_]*_)([0-9]+)\.dth', op.getFileName()) file_stem = file_parse.group(1) file_index = int( file_parse.group(2) ) # ok now we need to parse the header info header = get_Octopus_header(op.getDirectory(), file_stem, file_index) fi.nImages = len(header['N']) # check to see whether we have a bit depth, if not, assume 16-bit if 'Bit_Depth' in header: print header['Bit_Depth'] bit_depth = int(header['Bit_Depth'][0]) if bit_depth == 8: fi.fileType = FileInfo.GRAY8 else: bit_depth = 16 # will assume that all files have the same size fi.width = int( header['W'][0] ) fi.height = int( header['H'][0] ) file_timestamp = strftime("%a, %d %b %Y %H:%M:%S", gmtime(float(header['Time'][0])) ) # make a new imagestack to store the data stack = ImageStack(fi.width, fi.height) # finally, we need to make a list of files to import as sometimes we have # non contiguous file numbers try: files = os.listdir(op.getDirectory()) except IOError: raise IOError( "No files exist in directory: " + op.getDirectory()) filenums = [] for f in files: # strip off the stem, and get the number targetfile = re.match(file_stem+'([0-9]+)\.dth', f) # only take thosefiles which match the formatting requirements if targetfile: filenums.append( int(targetfile.group(1)) ) # sort the file numbers sorted_filenums = sorted(filenums) # make a file stats string file_stats_str = file_stem + '\n' + str(fi.width) +'x' + str(fi.height) + 'x' + \ str(len(sorted_filenums)) +' ('+str(bit_depth)+'-bit)\n' + file_timestamp # now open a dialog to let the user set options dlg = GenericDialog("Load Octopus Stream (v"+__version__+")") dlg.addMessage(file_stats_str) dlg.addStringField("Title: ", file_stem) dlg.addNumericField("Start: ", 1, 0); dlg.addNumericField("End: ", len(sorted_filenums), 0) dlg.addCheckbox("Open headers", True) dlg.addCheckbox("Contiguous stream?", False) dlg.addCheckbox("8-bit unsigned", bit_depth==8) dlg.showDialog() # if we cancel the dialog, exit here if dlg.wasCanceled(): return # set some params file_title = dlg.getNextString() file_start = dlg.getNextNumber() file_end = dlg.getNextNumber() DISPLAY_HEADER = bool( dlg.getNextBoolean() ) # check the ranges if file_start > file_end: file_start, file_end = file_end, file_start if file_start < 1: file_start = 1 if file_end > len(sorted_filenums): file_end = len(sorted_filenums) # now set these to the actual file numbers in the stream file_start = sorted_filenums[int(file_start)-1] file_end = sorted_filenums[int(file_end)-1] files_to_open = [n for n in sorted_filenums if n>=file_start and n<=file_end] # if we've got too many, truncate the list if (len(files_to_open) * fi.nImages * fi.width * fi.height) > (MAX_FRAMES_TO_IMPORT*512*512): dlg = GenericDialog("Warning") dlg.addMessage("This may use a lot of memory. Continue?") dlg.showDialog() if dlg.wasCanceled(): return False IJ.log( "Opening file: " + op.getDirectory() + op.getFileName() ) IJ.log( file_stats_str + "\nFile range: " + str(files_to_open[0]) + \ "-" + str(files_to_open[-1]) +"\n" ) # make a results table for the metadata # NOTE: horrible looping at the moment, but works if DISPLAY_HEADER: rt = ResultsTable() # ok now we can put the files together into the stack for i in files_to_open: # open the original .dat file and get the stack fi.fileName = get_Octopus_filename( op.getDirectory(), file_stem, i) if os.path.isfile( fi.fileName ): fo = FileOpener(fi) imp = fo.open(False).getStack() # put the slices into the stack for im_slice in xrange( imp.getSize() ): ip = imp.getProcessor( im_slice+1 ) if bit_depth == 8: bi = ip.getBufferedImage() else: bi = ip.get16BitBufferedImage() stack.addSlice( file_title, ip ) if DISPLAY_HEADER: header = get_Octopus_header(op.getDirectory(), file_stem, i) for n in xrange(len(header['N'])): rt.incrementCounter() for k in header.keys(): rt.addValue(k, parse_header( header[k][n] ) ) else: break # done! output = ImagePlus('Octopus ('+file_stem+')', stack) output.show() if DISPLAY_HEADER: rt.show("Octopus header metadata") return True
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()] nextStepImage = RGBStackMerge.mergeChannels(mergingImages,True) #nextStepImage.show() unbledImage.close() for img in mergingImages: img.close()
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 main(): # start with the sequence parameters fieldNames = ["Number of views", "Number of projections for each view", "Number of images for each projection (normally 1)", "Number of flats in each set", "Number of darks in each set", "Number of projections between each set of flats/darks"] fieldValues = [] # we start with zeros for the values # get user variables with imageJ dialog dialog = GenericDialog("Enter Scan Information") for i in range(6): dialog.addNumericField(fieldNames[i], 0, 0) dialog.addCheckbox("Two sets flats/darks between views?", False) dialog.showDialog() if dialog.wasCanceled(): return # exit function for i in range(6): fieldValues.append(int(dialog.getNextNumber())) extra = dialog.getNextBoolean() # make sure that none of the fields was left blank errmsg = "" for i in range(len(fieldNames)): if fieldValues[i] == "": errmsg += ('"%s" is a required field.\n\n' % fieldNames[i]) try: int(fieldValues[i]) except ValueError: errmsg += ('"%s" has to be an integer value.\n\n' % fieldNames[i]) if fieldValues[1] and fieldValues[5]: if int(fieldValues[1]) % int(fieldValues[5]) != 0: errmsg += ('Flat/Dark interval must divide evenly into projections\n\n') if errmsg != "": err_msg = GenericDialog("Error in Input") err_msg.addMessage(errmsg) err_msg.showDialog() return # exit if fieldValues is None: return # exit function fieldValues = [int(i) for i in fieldValues] # get the first item of the sequence using an imageJ dialog openFile = OpenDialog( "Select the first file of the sequence to rename.", None) fileName = openFile.getFileName() if fileName is None: return # exit function fileDir = openFile.getDirectory() first = fileDir + fileName path1, filename = os.path.split(first) basename = short(filename) # get directory for new files using imageJ dialog openOutDir = DirectoryChooser("Select directory for new files.") path2 = openOutDir.getDirectory() if path2 is None: return # exit function new_seq, fd_seq = gen_seq(fieldValues[0], fieldValues[1], fieldValues[2], fieldValues[3], fieldValues[4], fieldValues[5], extra) result = rename(basename, new_seq, fd_seq, path1, path2, fieldValues[0]) print result
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 settings(): """ Settings """ # Calls potential config file to set defaults # for settings dialog. Sets all defaults to 0 # if no config file exists. con_path = os.path.join(str(Root), "FRET_params.cfg") if os.path.exists(con_path): dflt = config_read() print type(dflt.get("b_sub", "Rolling ball")) print (dflt.get("b_sub", "Rolling ball")) print type(int(dflt.get("b_sub", "Rolling ball"))) print (dflt.get("b_sub", "Rolling ball")) else: dflt = {} feat_model_strings = ["Translation", "Rigid", "Similarity", "Affine ] reg_model_strings = ["Translation", "Rigid", "Similarity", "Affine", "Elastic", "Least Squares" ] b_sub_strings = ["Rolling Ball", "Manual Selection"] # Registration parameters dialog. gd = GenericDialog("Advanced Settings") gd.addMessage("REGISTRATION PARAMETERS") gd.addNumericField("Steps per scale octave: ", float(dflt.get("steps", 6)), 0, 7, "") gd.addNumericField("Max Octave Size: ", float(dflt.get("max_oct", 1024)), 0, 7, "") gd.addNumericField("Feature Descriptor Size: ", float(dflt.get("fd_size", 12)), 1, 7, "") gd.addNumericField("Initial Sigma: ", float(dflt.get("sigma", 1.2)), 2, 7, "") gd.addNumericField("Max Epsilon: ", float(dflt.get("max_eps", 15)), 1, 7, "") gd.addNumericField("Min Inlier Ratio: ", float(dflt.get("min_inlier", 0.05)), 3, 7, "") gd.addCheckbox("Use Shrinkage Constraint", ast.literal_eval(dflt.get("shrinkage", "False"))) gd.addChoice("Feature extraction model", feat_model_strings, feat_model_strings[int(dflt.get("feat_model", 1))] ) gd.addChoice("Registration model", reg_model_strings, reg_model_strings[int(dflt.get("reg_model", 1))] ) # Background removal parameters dialog. gd.addPanel(Panel()) gd.addMessage("BACKGROUND REMOVAL") gd.addChoice("Subtraction method:", b_sub_strings, b_sub_strings[int(dflt.get("b_sub", 0))] ) gd.addNumericField("Rolling ball size: ", float(dflt.get("ballsize", 50)), 1, 7, "px" ) gd.addCheckbox("Create Background", ast.literal_eval(dflt.get("create_b", "False"))) gd.addCheckbox("Light Background", ast.literal_eval(dflt.get("light_b", "False"))) gd.addCheckbox("Use Parabaloid", ast.literal_eval(dflt.get("parab", "False"))) gd.addCheckbox("Do Pre-smoothing", ast.literal_eval(dflt.get("smooth", "False"))) gd.addCheckbox("Correct Corners", ast.literal_eval(dflt.get("corners", "False"))) # Measumrent parameters dialog. gd.addPanel(Panel()) gd.addMessage("MEASUREMENT PARAMETERS") gd.addNumericField("Max Cell Area", float(dflt.get("cell_max", 2200)), 0, 7, "px") gd.addNumericField("Min Cell Area", float(dflt.get("cell_min", 200)), 0, 7, "px") gd.addNumericField("Ratio Subtraction", float(dflt.get("subtr_ratio", 0.31)), 3, 7, "") # Plot parameters dialog. gd.addPanel(Panel()) gd.addMessage("PLOT PARAMETERS") gd.addNumericField("Max y, d and aFRET", float(dflt.get("p_max", 0.65)), 2, 7, "") gd.addNumericField("Min y, d and aFRET", float(dflt.get("p_min", 0.0)), 2, 7, "") gd.addNumericField("Max y, norm. d and aFRET", float(dflt.get("p_max_n", 1.65)), 2, 7, "") gd.addNumericField("Min y, norm. d and aFRET", float(dflt.get("p_min_n", 0.5)), 2, 7, "") # Set location of dialog on screen. #gd.setLocation(0,1000) gd.showDialog() # Checks if cancel was pressed, kills script. if gd.wasCanceled() is True: sys.exit("Cancel was pressed, script terminated.") # Parameters dictionary. parameters = {"steps" : gd.getNextNumber(), "max_oct" : gd.getNextNumber(), "fd_size" : gd.getNextNumber(), "sigma" : gd.getNextNumber(), "max_eps" : gd.getNextNumber(), "min_inlier" : gd.getNextNumber(), "shrinkage" : gd.getNextBoolean(), "feat_model" : gd.getNextChoiceIndex(), "reg_model" : gd.getNextChoiceIndex(), "b_sub" : gd.getNextChoiceIndex(), "ballsize" : gd.getNextNumber(), "create_b" : gd.getNextBoolean(), "light_b" : gd.getNextBoolean(), "parab" : gd.getNextBoolean(), "smooth" : gd.getNextBoolean(), "corners" : gd.getNextBoolean(), "cell_max" : gd.getNextNumber(), "cell_min" : gd.getNextNumber(), "subtr_ratio" : gd.getNextNumber(), "p_max" : gd.getNextNumber(), "p_min" : gd.getNextNumber(), "p_max_n" : gd.getNextNumber(), "p_min_n" : gd.getNextNumber() } parameters = config_write(parameters) return parameters
def distance(x1, y1, x2, y2): sq1 = (x1 - x2) * (x1 - x2) sq2 = (y1 - y2) * (y1 - y2) dis = math.sqrt(sq1 + sq2) return (dis) while True: checkbox = False while checkbox == False: gd = GenericDialog("Title here") gd.addStringField("id", "") gd.addCheckbox("Same Image", True) gd.showDialog() checkbox = gd.getNextBoolean() id = gd.getNextString() if checkbox == False: IJ.run("Open Next") else: break imp = IJ.getImage() IJ.setTool("multipoint") WaitForUserDialog("make 11 points").show() proi = imp.getRoi() p = proi.getPolygon() xpts = p.xpoints ypts = p.ypoints
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
def run(): ### Default arguments two_sarcomere_size = 25 # determined by filter used. rotation_angle = 0.0 ### Get the image we'd like to work with. # Don't need to ask where to save the intermediate image since it'll just be saved in the matchedmyo folder anyway # may change this though. In case they want to keep that image around. this_img = WindowManager.getCurrentImage() if this_img == None: ud = WaitForUserDialog( "Please select the image you would like to analyze.") ud.show() this_img = WindowManager.getCurrentImage() img_name = this_img.getTitle() matchedmyo_path = "/home/AD/dfco222/scratchMarx/matchedmyo/" # this would be grabbed from the prompt gd = GenericDialog("Preprocessing Options") gd.addCheckbox("Automatic Resizing/Rotation", True) gd.addCheckbox("CLAHE", True) gd.addCheckbox("Normalization to Transverse Tubules", True) gd.showDialog() if gd.wasCanceled(): return auto_resize_rotate = gd.getNextBoolean() clahe = gd.getNextBoolean() normalize = gd.getNextBoolean() if auto_resize_rotate: # Clear selection so it takes FFT of full image rotation_angle = auto_resize_angle_measure(this_img, two_sarcomere_size) if clahe: clahe_args = "blocksize={} histogram=256 maximum=3 mask=*None* fast_(less_accurate)".format( two_sarcomere_size) IJ.run(this_img, "Enhance Local Contrast (CLAHE)", clahe_args) if normalize: # Ask the user to select a subsection of the image that looks healthy-ish. ud = WaitForUserDialog( "Please select a subsection exhibiting a measure of healthy TT structure using the Rectangle tool.\n" + " Only a single cell or several are needed.\n\n" + " Press 'OK' when finished.") ud.show() IJ.setTool("rectangle") # Duplicate the selected subsection. selection = this_img.crop() IJ.run(selection, "Duplicate...", "title=subsection.tif") # Grab the subsection image and rotate it. selection = WindowManager.getImage("subsection.tif") IJ.run( selection, "Rotate...", "angle={} grid=1 interpolation=Bicubic enlarge".format( rotation_angle)) # Ask the user to select a bounding box that contains only tubules # NOTE: Need to get rid of initial selection since it's the entire image and it's annoying to click out of IJ.setTool("rectangle") IJ.run(selection, "Select None", "") ud = WaitForUserDialog( "Select a subsection of the image that contains only tubules and no membrane." ) ud.show() # Grab the subsection ImagePlus selection = WindowManager.getCurrentImage() this_window = WindowManager.getActiveWindow() selection_small = selection.crop() IJ.run(selection, "Close", "") # NOTE: May not actually display this depending on how the macros work IJ.run(selection_small, "Duplicate...", "title=subsection_small.tif") # Smooth the selection using the single TT filter. # NOTE: It won't read in so we're just going to hard code it in since it's simple tt_filt_row = "0 0 0 1 1 1 1 1 1 0 0 0 0\n" tt_filt = "" for i in range(21): tt_filt += tt_filt_row IJ.run("Convolve...", "text1=[" + tt_filt + "] normalize") # Segment out the TTs from the 'gaps' using Gaussian Adaptive Thresholding. selection_small = WindowManager.getImage("subsection_small.tif") IJ.run(selection_small, "Duplicate...", "title=thresholded.tif") threshed = WindowManager.getImage("thresholded.tif") IJ.run(threshed, "Auto Local Threshold", "method=Bernsen radius=7 parameter_1=1 parameter_2=0 white") # Select the TTs from the thresholded image. IJ.run(threshed, "Create Selection", "") tt_selection = WindowManager.getImage("subsection_small.tif") IJ.selectWindow("thresholded.tif") IJ.selectWindow("subsection_small.tif") IJ.run(tt_selection, "Restore Selection", "") # Get TT intensity statistics. stat_options = IS.MEAN | IS.MIN_MAX | IS.STD_DEV stats = IS.getStatistics(tt_selection.getProcessor(), stat_options, selection_small.getCalibration()) # Calculate pixel ceiling intensity value based on heuristic. # TODO: Add a catch for data type overflow. pixel_ceiling = stats.mean + 3 * stats.stdDev print "px ceil:", pixel_ceiling # Invert selection to get inter-sarcomeric gap intensity statistics. IJ.run(tt_selection, "Make Inverse", "") stat_options = IS.MEAN | IS.MIN_MAX | IS.STD_DEV stats = IS.getStatistics(tt_selection.getProcessor(), stat_options, selection_small.getCalibration()) # Calculate pixel floor intensity value based on heuristic. pixel_floor = stats.mean - stats.stdDev # TODO: Add a catch for data type underflow. print "px floor:", pixel_floor # Threshold original image based on these values. IJ.selectWindow(this_img.getTitle()) IJ.run(this_img, "Select All", "") IJ.setMinAndMax(pixel_floor, pixel_ceiling) IJ.run(this_img, "Apply LUT", "") ## Ask if it is acceptable. gd = GenericDialog("Acceptable?") gd.addMessage( "If the preprocessed image is acceptable for analysis, hit 'OK' to being analysis.\n" + " If the image is unacceptable or an error occurred, hit 'Cancel'") gd.showDialog() if gd.wasCanceled(): return ## Save the preprocessed image. imp = IJ.getImage() fs = FileSaver(imp) img_save_dir = matchedmyo_path + "myoimages/" # actually get from user at some point img_file_path = img_save_dir + img_name[:-4] + "_preprocessed.tif" if os.path.exists(img_save_dir) and os.path.isdir(img_save_dir): print "Saving image as:", img_file_path if os.path.exists(img_file_path): # use dialog box to ask if they want to overwrite gd = GenericDialog("Overwrite?") gd.addMessage( "A file exists with the specified path, \"{}\". Would you like to overwrite it?" .format(img_file_path)) gd.enableYesNoCancel() gd.showDialog() if gd.wasCanceled(): return elif fs.saveAsTiff(img_file_path): print "Preprocessed image saved successfully at:", '"' + img_file_path + '"' else: print "Folder does not exist or is not a folder!" ### Create the YAML file containing the parameters for classification ## Ask user for YAML input gd = GenericDialog("YAML Input") gd.addStringField("imageName", img_file_path, 50) #gd.addStringField("maskName", "None") gd.addStringField("outputParams_fileRoot", img_file_path[:-4], 50) gd.addStringField("outputParams_fileType", "tif") gd.addNumericField("outputParams_dpi", 300, 0) gd.addCheckbox("outputParams_saveHitsArray", False) gd.addStringField("outputParams_csvFile", matchedmyo_path + "results/") gd.addCheckbox("TT Filtering", True) gd.addToSameRow() gd.addCheckbox("LT Filtering", True) gd.addToSameRow() gd.addCheckbox("TA Filtering", True) gd.addNumericField("scopeResolutions_x", 5.0, 3) gd.addToSameRow() gd.addNumericField("scopeResolutions_y", 5.0, 3) gd.addMessage("Enter in filter rotation angles separated by commas.") gd.addStringField("", "-25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25", 50) gd.addCheckbox("returnAngles", False) gd.addCheckbox("returnPastedFilter", True) gd.showDialog() if gd.wasCanceled(): return strings = [st.text for st in gd.getStringFields()] #if strings[1] == "None" or "": # strings[1] = None nums = [float(num.text) for num in gd.getNumericFields()] nums[0] = int(nums[0]) # Have to make sure the dpi variable is an integer checks = [str(bool(boo.state)) for boo in gd.getCheckboxes()] iter_argument = ','.join( [str(float(it) - rotation_angle) for it in strings[4].split(',')]) string_block = """imageName: {0[0]} outputParams: fileRoot: {0[1]} fileType: {0[2]} dpi: {1[0]} saveHitsArray: {2[0]} csvFile: {0[3]} preprocess: False filterTypes: TT: {2[1]} LT: {2[2]} TA: {2[3]} scopeResolutions: x: {1[1]} y: {1[2]} iters: [{3}] returnAngles: {2[4]} returnPastedFilter: {2[5]}""".format(strings, nums, checks, iter_argument) im_title = this_img.getTitle() with cd(matchedmyo_path): yaml_file_path = "./YAML_files/" + im_title[:-4] + ".yml" with open("./YAML_files/" + im_title[:-4] + ".yml", "w") as ym: ym.write(string_block) print "Wrote YAML file to:", matchedmyo_path + yaml_file_path[2:] ### Run the matchedmyo code on the preprocessed image with cd(matchedmyo_path): #os.chdir(matchedmyo_path) #subprocess.call(["python3", matchedmyo_path+"matchedmyo.py", "fullValidation"]) subprocess.call( ["python3", "matchedmyo.py", "run", "--yamlFile", yaml_file_path])
def processFile(): # start logging IJ.log("\n______________________________\n\n\t\tOlympus DM correction\n\t\tVersion " + pluginVersion +"\n______________________________\n") # ask user for file ofd = OpenDialog("Choose a file", None) filename = ofd.getFileName() if filename is None: IJ.log("User canceled the dialog!\nImage processing canceled!\n") return directory = ofd.getDirectory() filepath = directory + filename IJ.log("File path: " + filepath) if not filename.endswith(".oir"): IJ.log("Not an Olympus (.oir) file.\nNo image to process.\n") return filenameExExt = os.path.splitext(filename)[0] # parse metadata reader = ImageReader() omeMeta = MetadataTools.createOMEXMLMetadata() reader.setMetadataStore(omeMeta) reader.setId(filepath) numChannels = reader.getSizeC() numSlices = reader.getSizeZ() numFrames = reader.getSizeT() seriesCount = reader.getSeriesCount() globalMetadata = reader.getGlobalMetadata() seriesMetadata = reader.getSeriesMetadata() objLensName = globalMetadata['- Objective Lens name #1'] areaRotation = float(seriesMetadata['area rotation #1']) acquisitionValueRotation = float(seriesMetadata['acquisitionValue rotation #1']) if 'regionInfo rotation #1' in seriesMetadata: regionInfoRotation = float(seriesMetadata['regionInfo rotation #1']) else: regionInfoRotation = float(0) totalRotation = areaRotation + regionInfoRotation physSizeX = omeMeta.getPixelsPhysicalSizeX(0) physSizeY = omeMeta.getPixelsPhysicalSizeY(0) pxSizeX = physSizeX.value(UNITS.MICROM) pxSizeY = physSizeY.value(UNITS.MICROM) # log metadata IJ.log("\nMETADATA") #IJ.log("Filename: " + filepath) IJ.log("Number of series: " + str(seriesCount)) IJ.log("Number of channels: " + str(numChannels)) IJ.log("Number of frames: " + str(numFrames)) IJ.log("Number of slices: " + str(numSlices)) IJ.log("Objective lens: " + objLensName) IJ.log("FOV rotation: " + str(areaRotation)) IJ.log("ROI rotation: " + str(regionInfoRotation)) IJ.log("Total rotation: " + str(totalRotation)) IJ.log("Pixel size:") IJ.log("\t\tX = " + str(physSizeX.value()) + " " + physSizeX.unit().getSymbol()) IJ.log("\t\tY = " + str(physSizeY.value()) + " " + physSizeY.unit().getSymbol()) # 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("\nUser selected dichroic mirrors") for i in range(numChannels): IJ.log("\t\tChannel " + str(i+1) + ": " + dichroics[i]) 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("\nUser selected channel colours") mergeList = [] for i in range(len(colourChoices)): ch = gdMerge.getNextChoice() if ch == "NONE": mergeList.append(None) else: mergeList.append(chDict[ch]) IJ.log("\t\t" + colourChoices[i] + ": " + ch) # ask user for an output directory dc = DirectoryChooser("Choose folder for output") od = dc.getDirectory() if od is None: IJ.log("User canceled the dialog!\nImage processing canceled!\n") return if merge: tifDir = od + "." + str(datetime.now()).replace(" ", "").replace(":", "") + "/" if not os.path.exists(tifDir): os.makedirs(tifDir) IJ.log("\nCreated temporary folder: " + tifDir + "\n") else: IJ.log("Unable to create temporary folder!\n") else: tifDir = od + filenameExExt + "/" if not os.path.exists(tifDir): os.makedirs(tifDir) IJ.log("\nCreated subfolder: " + tifDir + "\n") else: IJ.log("\nSubfolder " + tifDir + " already exists") # correct images tifFilePaths = [] for i in range(numChannels): ip = extractChannel(oirFile=filepath, ch=i) if dichroics[i] == "DM1": IJ.log("Channel " + str(i+1) + " was imaged using DM1, so no correction required.") else: offsets = getOffset(obj=objLensName,dm=dichroicDict[dichroics[i]]) xom = offsets['x'] yom = offsets['y'] if abs(totalRotation) > 0.1: rotOff = rotateOffset(x=xom, y=yom, angle=-totalRotation) xom = rotOff['x'] yom = rotOff['y'] xop = int(round(xom/pxSizeX)) yop = int(round(yom/pxSizeY)) IJ.log("Channel " + str(i+1) + " offsets") IJ.log("\t\tMicrometres") IJ.log("\t\t\t\tx = " + str(xom)) IJ.log("\t\t\t\ty = " + str(yom)) IJ.log("\t\tPixels") IJ.log("\t\t\t\tx = " + str(xop)) IJ.log("\t\t\t\ty = " + str(yop)) IJ.run(ip, "Translate...", "x=" + str(-xop) + " y=" + str(-yop) + " interpolation=None stack") tifFilePath = tifDir + filenameExExt + "_ch_"+str(i+1)+".tif" tifFilePaths.append(tifFilePath) if os.path.exists(tifFilePath): IJ.log("\nOutput file exists: " + tifFilePath) IJ.log("Rerun plugin choosing a different output folder") IJ.log("or delete file and then rerun plugin.") IJ.log("Image processing terminated!\n") return FileSaver(ip).saveAsTiff(tifFilePath) if merge: for i in range(len(mergeList)): if mergeList[i] != None: mergeList[i] = readSingleChannelImg(tifFilePaths[mergeList[i]]) merged = RGBStackMerge.mergeChannels(mergeList, False) mergedChannelFilepath = od + filenameExExt + ".tif" if os.path.exists(mergedChannelFilepath): IJ.log("\nOutput file exists: " + mergedChannelFilepath) IJ.log("Rerun plugin choosing a different output folder") IJ.log("or delete file and then rerun plugin.") IJ.log("Image processing terminated!\n") FileSaver(merged).saveAsTiff(mergedChannelFilepath) for tf in tifFilePaths: os.remove(tf) os.rmdir(tifDir) IJ.log("\nFinished processing file:\n" + filepath + "\n") if merge: IJ.log("Image file with channels aligned:\n" + od + filenameExExt + ".tif\n") else: IJ.log("Aligned images (one tiff file for each channel) can be found in:\n" + tifDir + "\n")
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()
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
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))