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 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 getOK(text): gd = GenericDialog('User prompt') gd.addMessage(text) gd.hideCancelButton() gd.enableYesNoCancel() gd.showDialog() return gd.wasOKed()
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(): lowerThreshold = 80; upperThreshold = 255; stepNumber = 1 stepThreshold = 5; #p3DOCThreshold = 70; #p3DOCSlice = 1; p3DOCmin = 100; p3DOCmax = 2658480; gd = GenericDialog( "Parameters" ) gd.addMessage("Binary mask thresholds") gd.addNumericField("Lower Threshold", lowerThreshold, 0) # show 2 decimals gd.addNumericField("Upper threshold", upperThreshold, 0) # show 2 decimals gd.addNumericField("Step number", stepNumber, 0) # show 2 decimals gd.addNumericField("Step threshold", stepThreshold, 0) # show 2 decimals gd.addMessage("3D Object Counter parameters") #gd.addNumericField("threshold", p3DOCThreshold, 0) # show 2 decimals gd.addNumericField("min.", p3DOCmin, 0) # show 2 decimals gd.addNumericField("max.", p3DOCmax, 0) # show 2 decimals gd.showDialog() if gd.wasCanceled(): return # Read out the options lowerThreshold = gd.getNextNumber() upperThreshold = gd.getNextNumber() stepNumber = gd.getNextNumber() stepThreshold = gd.getNextNumber() #p3DOCThreshold = gd.getNextNumber() p3DOCmin = gd.getNextNumber() p3DOCmax = gd.getNextNumber() return lowerThreshold, upperThreshold, stepNumber, stepThreshold, p3DOCmin, p3DOCmax
def run(): ''' If someone tries to run this file by itself, warn them of their error. Unfortunately, since I was too lazy to make Microscope_Calibrations a full plugin (rather than a script), this accompanying settings file will show up in the Scripts menu.''' from ij.gui import GenericDialog gd = GenericDialog("Microscope_Calibrations_user_settings.py") gd.addMessage("This file is only for adding functionality to the plugin 'Microscope Measurement Tools'.\nNothing is done when this settings file is run by itself." ) gd.showDialog()
def run(): ''' If someone tries to run this file by itself, warn them of their error. Unfortunately, since I was too lazy to make Microscope_Calibrations a full plugin (rather than a script), this accompanying settings file will show up in the Scripts menu.''' from ij.gui import GenericDialog gd = GenericDialog("Microscope_Calibrations_user_settings.py") gd.addMessage("This file is only for setting the microscope calibrations and settings for the plugins 'Microscope Measurement Tools'.\nNothing is done when this settings file is run by itself.\nPlease open this file in a text editor instead, to edit the calibrations.\n \n" + \ "The file should reside in a path like the following\n" + \ "Fiji.app/plugins/Scripts/Analyze/Microscope Measurement Tools/Microscope_Calibrations_user_settings.py\n " + "\n" + \ "Changes to the settings file are not automatically picked up by Fiji. The workaround is to\n 1) Quit Fiji.\n 2) Delete the '$py.class' file 'Microscope_Calibrations_user_settings$py.class'\n 3) Open Fiji. Make sure the new settings show up in 'Choose Microscope Calibration'." ) gd.showDialog()
def get_metadata_table_filepath(): """Get a the metadata template filename""" d = GenericDialog("Metadata Template") d.addMessage("Please choose a metadata template") d.enableYesNoCancel("OK", "Cancel") d.hideCancelButton() d.showDialog() if d.wasOKed(): od = OpenDialog("Metadata File") return os.path.join(od.getDirectory(), od.getFileName()) else: return
def 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 get_options(): """Ask user for input values.""" dlg = GenericDialog("Options for Boxed Heatmap") dlg.addMessage("Boxed Heatmap settings") dlg.addMessage("Specify box size:") dlg.addNumericField("Width", 32, 0) dlg.addNumericField("Height", 32, 0) dlg.showDialog() if dlg.wasCanceled(): print "User canceled dialog." return None # Read out the options boxw = int(dlg.getNextNumber()) boxh = int(dlg.getNextNumber()) return boxw, boxh
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(): gd = GenericDialog("Options") gd.addMessage("Filter Parameters") gd.addNumericField("Smoothing Parameter", 0.1, 2) # show 2 decimals gd.addNumericField("Patch radius", 2 , 1) gd.addNumericField("Search volume radius", 3 , 1) gd.showDialog() if gd.wasCanceled(): print "User canceled dialog!" sys.exit() # Read out the options beta = gd.getNextNumber() patchradius = gd.getNextNumber() searchradius = gd.getNextNumber() return beta, patchradius, searchradius
def showTable(self): """ Add the main panel to a GenericDialog and show it """ gd = GenericDialog("Roi-group table") gd.addPanel(self) # Add current table instance to panel gd.addMessage("""If you use this plugin, please cite: Laurent Thomas. (2020, November 18). LauLauThom/RoiGroupTable: ImageJ/Fiji RoiGroup Table (Version 1.0) Zenodo. http://doi.org/10.5281/zenodo.4279049""") gd.addHelp(r"https://github.com/LauLauThom/RoiGroupTable") gd.showDialog() if gd.wasOKed(): # Update ImageJ Roi group names mapping stringGroup = self.tableModel.getGroupString() Roi.setGroupNames(stringGroup)
def get_parameters(p, num_data_sets): gd = GenericDialog("Correct 3D Drift Options") gd.addMessage("Found "+str(num_data_sets)+" data sets") gd.addStringField("analyse", "all"); gd.addMessage("Image analysis parameters:") for k in p.keys(): gd.addNumericField(k, p[k], 2); gd.showDialog() if gd.wasCanceled(): return to_be_analyzed = gd.getNextString() for k in p.keys(): p[k] = gd.getNextNumber() return to_be_analyzed, p
def getRefIdDialog(): gd = GenericDialog("Reference Image") gd.addMessage("Preparing Turboreg(Rigidbody)\nSpecify image for reference") gd.addNumericField("Channel (C):", 2, 0) gd.addNumericField("Slice (Z):", 1, 0) gd.addNumericField("Frame (T):", 1, 0) gd.addMessage("Note: All fields start with 1 (not 0)") gd.showDialog() # if gd.wasCanceled(): print "User canceled dialog!" return # Read out the options c = int(gd.getNextNumber()) z = int(gd.getNextNumber()) t = int(gd.getNextNumber()) refId = [c,z,t] return refId
def get_image(info, default_path, used_files): """handle getting image from file""" check_for_file_overlap_OK = False; while not check_for_file_overlap_OK: info.set_input_file_path(file_location_chooser(default_path)); if info.get_input_file_path() in used_files: dlg = GenericDialog("Image already used..."); dlg.addMessage("This image has already been used in this analysis run. \n " + "Continue with this image, or choose a new one?"); dlg.setOKLabel("Continue"); dlg.setCancelLabel("Choose again..."); dlg.showDialog(); check_for_file_overlap_OK = False if dlg.wasCanceled() else True; else: check_for_file_overlap_OK = True; import_opts, info = choose_series(info.get_input_file_path(), info) imps = bf.openImagePlus(import_opts); imp = imps[0]; try: memory_usage = IJ.currentMemory()/IJ.maxMemory(); print("memory usage = " +str(memory_usage)); # arbitrary limit... if memory_usage > 0.95: IJ.run(imp, "8-bit", ""); print("WARNING - IMAGE CONVERTED TO 8 BIT TO CONSERVE MEMORY!"); info.set_metadata_file_path(os.path.splitext(info.get_input_file_path())[0] + ".txt"); metadata = import_iq3_metadata(info.get_metadata_file_path()); IJ.run(imp, "Properties...", "channels=" + str(int(metadata['n_channels'])) + " slices=" + str(int(metadata['z_pixels'])) + " frames=1 unit=" + str(metadata['x_unit']) + " pixel_width=" + str(metadata['x_physical_size']) + " pixel_height=" + str(metadata['y_physical_size']) + " voxel_depth=" + str(metadata['z_extent']/metadata['z_pixels'])); info.set_xy_pixel_size_um(metadata['x_physical_size']); info.set_z_plane_spacing_um(metadata['z_extent']/metadata['z_pixels']); info = parse_info_from_filename(info); except e as Exception: print(e.message); finally: if imp is not None: imp.close(); return imp, info;
def run(): bPrintLog(' ', 0) bPrintLog('=====================================', 0) bPrintLog('Running bAlign_Batch_v7', 0) bPrintLog('=====================================', 0) if len(sys.argv) < 2: print " We need a hard-drive folder with .tif stacks as input" print " Usage: ./fiji-macosx bALign_Batch_7 <full-path-to-folder>/" # Prompt user for a folder sourceFolder = DirectoryChooser( "Please Choose A Directory Of .tif Files").getDirectory() if not sourceFolder: return 0 strippedFolder = sourceFolder.replace(' ', '') if sourceFolder != strippedFolder: print 'found a space in specified path. Pease remove spaces and try again.' print 'path:', sourceFolder errorDialog = GenericDialog('Align Batch 7 Options') errorDialog.addMessage('bAlignBatch7 Error !!!') errorDialog.addMessage('There can not be any spaces in the path.') errorDialog.addMessage('Please remove spaces and try again.') errorDialog.addMessage('Offending path is:') errorDialog.addMessage(sourceFolder) errorDialog.showDialog() return 0 else: sourceFolder = sys.argv[1] #assuming it ends in '/' if not os.path.isdir(sourceFolder): bPrintLog('\nERROR: run() did not find folder: ' + sourceFolder + '\n', 0) return 0 if (Options(sourceFolder)): runOneFolder(sourceFolder) bPrintLog('=====================================', 0) bPrintLog('Done bAlign_Batch_v7', 0) bPrintLog('=====================================', 0) bPrintLog(' ', 0)
def runGUI(): defaultRad = 20 defaultNCols = 20 defaultNRows = 5 gd = GenericDialog("Blobber - v0.1 alpha") gd.addMessage( "\tBlobber is a generic spot array analyzer \n\t\t\t\t\t\t\t\t\t\t\t\t\t(copyright Artur Yakimovich 2019)\n\n" ) gd.addNumericField("Number_of_columns", defaultNCols, 0) gd.addNumericField("Number_of_rows", defaultNRows, 0) gd.addNumericField("Circle_radius_(px)", defaultRad, 0) nCols = int(gd.getNextNumber()) nRows = int(gd.getNextNumber()) rad = int(gd.getNextNumber()) gd.showDialog() if gd.wasCanceled(): return None runScript(nCols, nRows, rad)
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 run(): bPrintLog(' ', 0) bPrintLog('=====================================', 0) bPrintLog('Running bAlign_Batch_v7', 0) bPrintLog('=====================================', 0) if len(sys.argv) < 2: print " We need a hard-drive folder with .tif stacks as input" print " Usage: ./fiji-macosx bALign_Batch_7 <full-path-to-folder>/" # Prompt user for a folder sourceFolder = DirectoryChooser("Please Choose A Directory Of .tif Files").getDirectory() if not sourceFolder: return 0 strippedFolder = sourceFolder.replace(' ', '') if sourceFolder != strippedFolder: print 'found a space in specified path. Pease remove spaces and try again.' print 'path:', sourceFolder errorDialog = GenericDialog('Align Batch 7 Options') errorDialog.addMessage('bAlignBatch7 Error !!!') errorDialog.addMessage('There can not be any spaces in the path.') errorDialog.addMessage('Please remove spaces and try again.') errorDialog.addMessage('Offending path is:') errorDialog.addMessage(sourceFolder) errorDialog.showDialog() return 0 else: sourceFolder = sys.argv[1] #assuming it ends in '/' if not os.path.isdir(sourceFolder): bPrintLog('\nERROR: run() did not find folder: ' + sourceFolder + '\n',0) return 0 if (Options(sourceFolder)): runOneFolder(sourceFolder) bPrintLog('=====================================', 0) bPrintLog('Done bAlign_Batch_v7', 0) bPrintLog('=====================================', 0) bPrintLog(' ', 0)
def get_config_file(folder): '''Returns the config file name.''' # Get list of files in the selected directory. files = os.listdir(folder) # Check if a config file is present in folder. if default_config in files: dialog = GenericDialog('Default config file found!') dialog.addMessage('Use this file for the analysis?\n \n%s' % os.path.join(folder, default_config)) dialog.enableYesNoCancel() dialog.showDialog() if dialog.wasCanceled(): return None elif dialog.wasOKed(): return default_config else: open_dialog = OpenDialog('Select a config file', folder, default_config) return open_dialog.getFileName() else: # Ask user to select a config file. open_dialog = OpenDialog('Select a config file', folder, default_config) return open_dialog.getFileName()
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 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 get_parameters(p, keys, num_data_sets): gd = GenericDialog("Please enter parameters") gd.addMessage("Found "+str(num_data_sets)+" data sets") gd.addStringField("analyse", "all"); gd.addMessage("Image analysis parameters:") gd.addMessage("Please note: the threshold values are inclusive!\nThus, to exlude pixels with value 255 the upper threshold needs to be 254") for k in keys: gd.addNumericField(k, p[k], 2); gd.showDialog() if gd.wasCanceled(): return to_be_analyzed = gd.getNextString() for k in keys: p[k] = gd.getNextNumber()
from ij.gui import GenericDialog import sys from java.lang.System import getProperty sys.path.append(getProperty("fiji.dir") + "/plugins/CMTK_Registration") gd = GenericDialog('About CMTK GUI') gd.addMessage('CMTK GUI is open source software released under GPLv3') gd.addMessage('CMTK GUI is independently developed by Greg Jefferis and is NOT supported by CMTK team') gd.setCancelLabel("CMTK GUI Web Page") gd.showDialog() if gd.wasCanceled(): from ij import IJ IJ.runPlugIn("ij.plugin.BrowserLauncher", "https://github.com/jefferis/fiji-cmtk-gui")
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
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()
dc = DirectoryChooser("Choose directory with OME.TIF files...") sourceDir = dc.getDirectory() if not(sourceDir is None): if not os.path.exists(sourceDir + "resized"): os.mkdir(sourceDir + "resized") dirSize = get_directory_size(sourceDir) dirSizeMB = dirSize / 1048576 memoryObj = Memory() memFiji = memoryObj.maxMemory() memFijiMB = memFiji / 1048576 gd = GenericDialog("Set Parameters...") gd.addNumericField("Sizing_ratio (Final disk space / Initial disk space):",0.25,2) gd.addMessage("Directory size: " + str(dirSizeMB) + "MB") gd.addMessage("Maximum memory: " + str(memFijiMB) + "MB") mem_recs = calculate_memory_recs(dirSize,memFiji) print mem_recs for i in range(0,len(mem_recs)): ratio_rec = float(mem_recs[i]) / dirSizeMB if (ratio_rec > 1): ratio_rec = 1 print ratio_rec ratio_rec_str = "%.3f" % ratio_rec gd.addMessage(str(i+1)+"-channel: " + str(mem_recs[i]) + "MB; Ratio: " + ratio_rec_str) gd.showDialog() ratioRaw = gd.getNextNumber() ratio = math.sqrt(ratioRaw) if (gd.wasOKed()):
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 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
import re import os from ij.io import DirectoryChooser from ij.io import OpenDialog from ij.gui import GenericDialog from ij import IJ dc = DirectoryChooser("Choose directory with image tiles you want to stitch...") sourceDir = dc.getDirectory() opener = OpenDialog("Select DMI metadata file...",sourceDir,"tile_info.txt") metadata_file = opener.getPath() gd = GenericDialog("Input image name...") gd.addStringField("Image_prefix:","IMGid") gd.addMessage("Input directory: " + sourceDir) gd.showDialog() img_name = gd.getNextString() outputPath = sourceDir + img_name + "_seq" if sourceDir is not None and metadata_file is not None: ## computes tiling information from DMI metadata metadata = IJ.openAsString(metadata_file) p = re.compile(r'X Tiles: (\d+)') m = p.search(metadata) if m is None: xtiles = 0 else: xtiles = int(m.group(1)) p = re.compile(r'Y Tiles: (\d+)')
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(): '''This is the main function run when the plugin is called.''' #print dir(IJ) ip = IJ.getProcessor() imp = IJ.getImage() # get the current Image, which is an ImagePlus object #print "imp=", type(imp), imp #print dir(imp) roi = imp.getRoi() # get the drawn ROI #print "roi=", roi, roi.getClass() # check ROI type if roi==None: gd = GenericDialog("Draw Measurement - Line") gd.addMessage("Please draw a straight-line first!") gd.showDialog() return #raise Exception( "Please draw a line ROI first!" ) if roi.getTypeAsString() != "Straight Line": gd = GenericDialog("Draw Measurement - Line") gd.addMessage("Please draw a straight-line first!") gd.showDialog() return #raise Exception( "Not a Line ROI! (type="+roi.getTypeAsString()+")" ) p1 = [ int(roi.x1d), int(roi.y1d) ] # point 1 (x,y) p2 = [ int(roi.x2d), int(roi.y2d) ] # point 2 print "DrawMeas(): Line Points: p1=", p1, " & p2=", p2 pm = midpoint(p1, p2) # get midpoint coord # set ROI params from settings: ''' Using new method - used ip.drawLine instead of roi.draw, since roi.draw didn't always apply the line thickness. Would be best to use the ROI method, in case other types of ROI's could be annotated. roi.setStrokeWidth( sets.linethickness ) roi.setStrokeColor( jColor(float(sets.linecolor[0]), float(sets.linecolor[1]), float(sets.linecolor[2]), float(sets.linecolor[3])) ) #roi.drawPixels( ip ) # draw along the ROI - only draws outline unfortunately ip.drawRoi(roi) # draw the ROI on the image ''' ip.setLineWidth( int(sets.linethickness) ) ip.setColor( jColor(float(sets.linecolor[0]), float(sets.linecolor[1]), float(sets.linecolor[2]), float(sets.linecolor[3])) ) #ip.draw(roi) # changed to ip.drawLine() ip.drawLine( int(roi.x1d), int(roi.y1d), int(roi.x2d), int(roi.y2d) ) '''Draw text annotation''' unit = imp.getCalibration().getUnit().encode('utf8') # get the unit as UTF-8 (for \mu) print "Draw_Meas(): Unit (raw) = `", unit,"`", type(unit), if unit[0] == u'\xc2': unit=unit[1:] # strip weird char at start of \mu # format of measurement text (eg. 3 decimal points): lenstr = "%0.3f" % roi.getLength() + " %s" % (unit) # string to print as length print "DrawMeas(): Line length= %s" % lenstr #print "x,y=", p2[0], p2[1] '''determine position of text from line coords, eg "bottom right" or "top left" etc. ''' # y-coord: if p2[1] > p1[1]: posstr = 'bottom' else: posstr = 'top' # x-coord: if p2[0] > p1[0]: posstr += ' right' else: posstr += ' left' drawText( lenstr, p2[0], p2[1], position=posstr ) imp.updateAndDraw() #update the image
from ij.gui import GenericDialog import sys from java.lang.System import getProperty sys.path.append(getProperty("fiji.dir") + "/plugins/CMTK_Registration") gd = GenericDialog('About CMTK') gd.addMessage('CMTK Registration suite is open source software released under GPLv3',) gd.addMessage('Currently installed CMTK version: '+cmtkgui.installed_version()) gd.addMessage('CMTK binary directory: '+cmtkgui.bin_dir()) gd.setCancelLabel("CMTK Web Page") gd.showDialog() if gd.wasCanceled(): from ij import IJ IJ.runPlugIn("ij.plugin.BrowserLauncher", "http://www.nitrc.org/projects/cmtk/")
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))
tiles = make_tile_series(xs,ys,xtiles,ytiles) print tiles # Copies tiles for stitching into temp directory and stitches, if necessary if len(tiles)==1: 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: