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(): global listener, xlist, ylist, zlist, manager gd = GenericDialog("Target Selection") gd.addChoice('type', ['point', 'circle', 'spiral'], 'point') gd.addNumericField(" power (%)", 85, 0) gd.addNumericField(" duration (ms)", 1, 0) gd.addNumericField(" radius(circle/spiral)", 5, 0) gd.addNumericField(" # revolutions (circle/spiral)", 3, 0) gd.addNumericField( " add CAMERA_TRIGGER after every (entries)", 1, 0) gd.addNumericField(" Prewait between entries (ms)", 5000, 0) gd.addNumericField(" Z-start of stack (um)", 0, 0) gd.addNumericField(" Z-step of stack (um)", 5, 0) gd.addMessage('Press ENTER to save\n') gd.addMessage('Press ESC to restart\n') gd.showDialog() profileType = gd.getNextChoice() power = gd.getNextNumber() duration = gd.getNextNumber() r = gd.getNextNumber() Nturns = gd.getNextNumber() camTriggerEvery = gd.getNextNumber() prewait = gd.getNextNumber() zStart = gd.getNextNumber() zStep = gd.getNextNumber() if gd.wasCanceled(): IJ.setTool(Toolbar.RECTANGLE) return else: return r, power, profileType, duration, Nturns, camTriggerEvery, zStart, zStep, prewait
def getRefChannel(channels, text = 'Reference Channel'): #dialog prompt to choose the reference channel gd = GenericDialog(text) gd.addChoice("output as", channels, channels[0]) gd.showDialog() if gd.wasCanceled(): print "User canceled dialog!" return return gd.getNextChoice()
def Resize(imp): gd = GenericDialog("Image size") scales = ["1024","2048","4096"] gd.addChoice("Choose image size",scales,scales[1]) gd.showDialog() scale_choice = gd.getNextChoice() IJ.run(imp,"Scale...", "x=- y=- z=1.0 width="+scale_choice+" height="+scale_choice+" interpolation=Bilinear average process create title=Scaled") scaled_imp = WindowManager.getImage("Scaled") return scaled_imp
def 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 choose_analysis_mode(params): """present UI for choosing how cells should be identified""" dialog = GenericDialog("Analysis methods") dialog.addMessage("Please choose how cell shape anlaysis should proceed:") dialog.addChoice("Analysis mode: ", params.list_analysis_modes(), params.last_analysis_mode) dialog.addMessage("") dialog.addChoice("GFP segmentation method: ", AutoThresholder.getMethods(), params.last_threshold_method) dialog.addNumericField("Minimum cell area (um" + _squared + "): ", params.last_minimum_cell_area_um2, 0) # dl = AnalysisModeListener() # dialog.addDialogListener(dl) dialog.showDialog() if dialog.wasCanceled(): print("Run canceled") return None, None, None return dialog.getNextChoice(), dialog.getNextChoice( ), dialog.getNextNumber()
def choose_analysis_mode(params): """present UI for choosing how cells should be identified""" dialog = GenericDialog("Analysis methods") dialog.addMessage("Please choose how cell shape anlaysis should proceed:") dialog.addChoice("Analysis mode", params.list_analysis_modes(), params.last_analysis_mode) dialog.showDialog() if dialog.wasCanceled(): raise KeyboardInterrupt("Run canceled") return dialog.getNextChoice()
def getOptions(): gd = GenericDialog("Loci Distance to compartment option") gd.addChoice("Compartment Channel", ["1","2","3","4"], "1") gd.addNumericField("Compartment Threshold",0.60,2) gd.addChoice("Loci Channel", ["1","2","3","4"], "2") gd.addNumericField("Compartment Threshold",0.60,2) gd.showDialog() # if gd.wasCanceled(): print "User canceled dialog!" return # # Read out the options speck_ch= int(gd.getNextChoice()) speck_th = gd.getNextNumber() loci_ch= int(gd.getNextChoice()) loci_th = gd.getNextNumber() return speck_ch,speck_th, loci_ch, loci_th
def make_directory(imgDir): """ Makes the necessary output directories or overwrites current ones. """ if not path.exists(imgDir) or not path.isdir(imgDir): print "Not a valid directory" exit(0) if not path.exists(imgDir+"/binary"): mkdir(imgDir+"/binary") else: gd = GenericDialog("Confirm Overwrite") choices = ["Yes", "No"] gd.addChoice("Overwrite \"binary\" folder?", choices, choices[0]) gd.showDialog() if gd.wasCanceled(): exit(0) choice = gd.getNextChoice() if choice == "No": exit(0) shutil.rmtree(imgDir+"/binary") mkdir(imgDir+"/binary") if not path.exists(imgDir+"/greyscale"): mkdir(imgDir+"/greyscale") else: gd = GenericDialog("Confirm Overwrite") choices = ["Yes", "No"] gd.addChoice("Overwrite \"greyscale\" folder?", choices, choices[0]) gd.showDialog() if gd.wasCanceled(): exit(0) choice = gd.getNextChoice() if choice == "No": exit(0) shutil.rmtree(imgDir+"/greyscale") mkdir(imgDir+"/greyscale")
def getRef(self, event): """ Dialog to update ref image attribute when get_ref button is pressed """ self.checkImages() gd = GenericDialog("Choose a reference image") gd.addChoice("Reference image", [Image.title for Image in self.Images.values()], self.Images.values() [0].title) # add all Image instances to a drop-down list gd.showDialog() ref_image_name = gd.getNextChoice() ref_image_ID = WM.getImage(ref_image_name).getID() self.ref_image = self.Images[ ref_image_ID] # update ref_image attribute IJ.log("Reference image is " + self.ref_image.title)
def getChannels(): gd = GenericDialog( "Select stack's channels" ) # print gd.getModalityType() # gd.setModal( False ) # print gd.getModalityType() color = ["red", "green", "blue"] gd.addChoice("Channel for mask", color, color[2]) gd.addChoice("Channel for particles", color, color[1]) gd.showDialog() maskChannel = gd.getNextChoice() partChannel = gd.getNextChoice() if gd.wasCanceled(): sys.exit() return maskChannel, partChannel
def make_directory(imgDir): """ Makes the necessary output directories or overwrites current ones. """ if not path.exists(imgDir) or not path.isdir(imgDir): print "Not a valid directory" exit(0) if not path.exists(imgDir + "/binary"): mkdir(imgDir + "/binary") else: gd = GenericDialog("Confirm Overwrite") choices = ["Yes", "No"] gd.addChoice("Overwrite \"binary\" folder?", choices, choices[0]) gd.showDialog() if gd.wasCanceled(): exit(0) choice = gd.getNextChoice() if choice == "No": exit(0) shutil.rmtree(imgDir + "/binary") mkdir(imgDir + "/binary") if not path.exists(imgDir + "/greyscale"): mkdir(imgDir + "/greyscale") else: gd = GenericDialog("Confirm Overwrite") choices = ["Yes", "No"] gd.addChoice("Overwrite \"greyscale\" folder?", choices, choices[0]) gd.showDialog() if gd.wasCanceled(): exit(0) choice = gd.getNextChoice() if choice == "No": exit(0) shutil.rmtree(imgDir + "/greyscale") mkdir(imgDir + "/greyscale")
def 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 save_etc(imp, info, output_folder): """handle saving output, final labelling and UI of what to do next""" dialog = GenericDialog("Marksl1 cell shape prescreen"); dialog.addChoice("Vessel type: ", info.get_vessel_types(), info.get_vessel_type()); dialog.addStringField("Channel 1 label: ", info.get_ch1_label()); dialog.addStringField("Channel 2 label: ", info.get_ch2_label()); dialog.addStringField("Experiment identifier: ", info.get_experiment_id()); dialog.addStringField("Embryo identifier: ", info.get_embryo_id()); dialog.setOKLabel("Save preprocessing"); dialog.showDialog(); info.set_vessel_type(dialog.getNextChoice()); info.set_ch1_label(dialog.getNextString()); info.set_ch2_label(dialog.getNextString()); info.set_experiment_id(dialog.getNextString()); info.set_embryo_id(dialog.getNextString()); if dialog.wasCanceled(): return "stop"; if dialog.wasOKed(): exsting_files = os.listdir(output_folder); r = re.compile(".*" + info.get_embryo_id() + " " + info.get_vessel_type() + ".*") fns = filter(r.match, exsting_files) numbers = list((int(s) for fn in fns for s in re.findall(r'\b\d+$', os.path.splitext(fn)[0]))); append_digit = (max(numbers) + 1) if numbers else 1; ch1str = (info.get_ch1_label() + " ") if info.get_ch1_label() else ""; ch2str = (info.get_ch2_label() + " ") if info.get_ch2_label() else ""; expstr = (info.get_experiment_id() + " ") if info.get_experiment_id() else ""; file_name = ("Cropped " + ch1str + ch2str + expstr + "e" + str(info.get_embryo_id()) + " " + info.get_vessel_type() + " " + str(append_digit)); FileSaver(imp).saveAsTiff(os.path.join(output_folder, (file_name + ".tif"))); info.save_info_to_json(os.path.join(output_folder, (file_name + ".json"))); continueDialog = YesNoCancelDialog(WM.getCurrentWindow(), "Continue?", "Continue with same input image or a new input image?", "New image...", "Same image"); if continueDialog.cancelPressed(): return "stop"; if continueDialog.yesPressed(): return "continue_newimage"; return "continue_sameimage"; return "stop";
def getOptionsDialog(self, imp): thr_methods = ["None", "Default", "Huang", "Intermodes", "IsoData", "Li", "MaxEntropy","Mean", "MinError(I)", "Minimum", "Moments", "Otsu", "Percentile", "RenyiEntropy", "Shanbhag" , "Triangle", "Yen"] gd = GenericDialog("Please select channels to collocalize") for i in range(1, imp.getNChannels() + 1): gd.addChoice("Threshold method for channel %i" % i, thr_methods, "None") gd.showDialog() if gd.wasCanceled(): self.exit() channels = [] for i in range(1, imp.getNChannels() + 1): method = gd.getNextChoice() self.methods.append(method) if method != "None": channels.append(i) for x in channels: for y in channels: if x < y: self.pairs.append((x, y))
def getThresholds(): thresholds = {} gd = GenericDialog("Threshold options") gd.addChoice("How would you like to set your thresholds?", ["default", "use threshold csv file"], "default") gd.showDialog() choice = gd.getNextChoice() log.write("Option: " + choice + "\n") if choice == "use threshold csv file": path = OpenDialog("Open the thresholds csv file") log.write("File used: " + path.getPath() + "\n") with open(path.getPath()) as csvfile: reader = csv.DictReader(csvfile) for row in reader: thresholds = row return thresholds
def get_color(nChannel=n_Channel): color_strings = [ "Green", "Magenta", "Cyan", "Blue", "Red", "Yellow", "Orange", "Gray", "Black" ] gd = GenericDialog("Set Colors") for i in range(nChannel): gd.addChoice("Channel {}".format(i + 1), color_strings, color_strings[i]) gd.showDialog() if gd.wasCanceled(): return else: selected_colours = [gd.getNextChoice() for _ in range(nChannel)] return selected_colours
def 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 getNames(): names = {} gd = GenericDialog("Naming options") gd.addChoice("How would you like to name your results for each well?", ["default", "use name convention csv file"], "default") gd.showDialog() choice = gd.getNextChoice() log.write("Option: " + choice + "\n") if choice == "use name convention csv file": path = OpenDialog("Open the names csv file") log.write("File used: " + path.getPath() + "\n") with open(path.getPath()) as csvfile: reader = csv.DictReader(csvfile) for row in reader: names[row['Row']] = row return names
def getOptions(): global listener, xlist, ylist, zlist, manager gd = GenericDialog("Target Selection") gd.addMessage('Mandatory parameters\n') gd.addChoice('type', ['point', 'circle', 'spiral'], 'point') gd.addNumericField(" power (%)", 85, 0) gd.addNumericField(" duration (millisec)", 3, 0) gd.addNumericField(" interval between entries (ms)", 5000, 0) gd.addNumericField(" Z-start of stack (microns)", 0, 0) gd.addNumericField(" Z-step of stack (microns)", 5, 0) gd.addMessage('Optional\n') gd.addNumericField(" radius of a circle/spiral", 5, 0) gd.addNumericField(" num. of turns per circle/spiral", 3, 0) gd.addNumericField(" take image after every .. entries", 1, 0) gd.addNumericField(" add offset to X coordinates", 0, 0) gd.addNumericField(" add offset to Y coordinates", 0, 0) gd.addNumericField( " imaging stack # for excitation onset (0,1,..)", 0, 0) gd.addMessage('Press ENTER to save the coordinate file\n') gd.addMessage('Press ESC to restart\n') gd.showDialog() profileType = gd.getNextChoice() power = gd.getNextNumber() duration = gd.getNextNumber() prewait = gd.getNextNumber() zStart = gd.getNextNumber() zStep = gd.getNextNumber() r = gd.getNextNumber() Nturns = gd.getNextNumber() camTriggerEvery = gd.getNextNumber() xOffset = gd.getNextNumber() yOffset = gd.getNextNumber() tmIndex = gd.getNextNumber() if gd.wasCanceled(): IJ.setTool(Toolbar.RECTANGLE) return else: return r, power, profileType, duration, Nturns, camTriggerEvery, zStart, zStep, prewait, xOffset, yOffset, tmIndex
def getNames(): info = [] gd = GenericDialog("Naming options") gd.addChoice("How would you like to output your results?", ["default", "use information csv file"], "default") gd.showDialog() choice = gd.getNextChoice() log.write("Option: " + choice + "\n") if choice == "use information csv file": path = OpenDialog("Open the names csv file") log.write("File used: " + path.getPath() + "\n") with open(path.getPath()) as csvfile: reader = csv.DictReader(csvfile) for row in reader: info.append(row) return info
def 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
gd = GenericDialog("Insert values") gd.addStringField("1. channel (DAPI/Tub)", 'c1') gd.addNumericField("1. channel lower threshold: ", 0, 0) gd.addStringField("2. channel", 'c2') gd.addNumericField("2. channel lower threshold: ", 0, 0) gd.addChoice("Quantify by:", ["Tubulin area", "DAPI #"], '') gd.showDialog() # Assign values from dialog channel1, channel2 = gd.getNextString(), gd.getNextString() lowth1, lowth2 = gd.getNextNumber(), gd.getNextNumber() # Check if the chosen folder has subdirectories, or simply just a folder with pictures for root, dirs, files in os.walk(directory, topdown=True): if dirs: data, sub = getfilesDIRS() break else: data, sub = getfilesNoDIRS() break #If the chosen directory does not contain ORG files; output error if len(data[0]) != 2: sys.exit("Channels should be written as ex 'c1'") #Initialize quantification, according to previous choice if gd.getNextChoice() == "Tubulin area": analyzeTUB() else: analyzeDAPI()
from ij.process import ImageProcessor from ij.process import ImageConverter from ij.gui import WaitForUserDialog from ij.gui import GenericDialog from ij.plugin.frame import RoiManager from ij.plugin.filter import ParticleAnalyzer # Set Threshold mode thresholdMode = False gd = GenericDialog("Set Threshold Mode") gd.addChoice("Would you like to enable thresholding mode?", ["Yes, enable thresholding mode"], "No, run the normal macro", "Yes") gd.showDialog() if gd.getNextChoice() == "Yes, enable thresholding mode": thresholdMode = True # Set watershed watershedMode = False gd = GenericDialog("Set Watershed Mode") gd.addChoice("Would you like to enable watershedding?", ["No, do not watershed", "Yes, enable watershed"], "No") gd.showDialog() if gd.getNextChoice() == "Yes, enable watershed": watershedMode = True #Set invert
# save roi if rm.getCount() != 0: rm.runCommand('Save', os.path.join(result_path, 'Roi.zip')) zimp.close() imp.close() rm.close() zrt.reset() if __name__ in ['__builtin__','__main__']: # ask file path via dialog open_file_dialog = OpenDialog('Opend file') path = open_file_dialog.getPath() # ask parameter via dialog parameter_dialog = GenericDialog('Parameter setting') parameter_dialog.addNumericField('Frame number', 1000,0) parameter_dialog.addNumericField('Frame rate (frame/s)', 100, 1) parameter_dialog.addChoice('Are motor rotation direction and cell rotation direction on image same?', ['Same', 'Different'], 'Same') parameter_dialog.showDialog() frame_number = int(parameter_dialog.getNextNumber()) frame_rate = 100.0 choice = parameter_dialog.getNextChoice() if choice == 'Same': CCW = 1 else: CCW = -1 tethered_cell(path, frame_number, frame_rate, CCW) IJ.log('analysis finished')
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 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))
computedImage = reduce(self.addImages,imgList) computedImage.show() IJ.showStatus("Ready") ## Main body of script opener = OpenDialog("Select parent LSM file...") parentLSMFilePath = opener.getPath() if (parentLSMFilePath is not None): stackInfo = parse_tile_info_file(parentLSMFilePath + "_tiles/tile_info.txt") channelTexts = map(lambda x: str(x), filter(lambda x:os.path.isfile(parentLSMFilePath+"_tiles/objects/C"+str(x)+".objects.keep.unique.csv"),range(1,stackInfo[0]+1))) gd = GenericDialog("Specify parameters...") gd.addChoice("Which_channel",channelTexts,channelTexts[0]) gd.showDialog() if gd.wasOKed(): channel = int(gd.getNextChoice()) ## Obtains global coordinate system for tiles scale_info = estimate_scale_multiplier(parentLSMFilePath+"_tiles/tile_1.ome.tif",parentLSMFilePath+"_tiles/resized/tile_1.tif") ## Parses each of the object files objectDB = [[] for x in range(4)] objectDB[0] = parse_object_file_into_db(parentLSMFilePath+"_tiles/objects/C"+str(channel)+".objects.keep.contained.csv") objectDB[1] = parse_object_file_into_db(parentLSMFilePath+"_tiles/objects/C"+str(channel)+".objects.keep.duplicated.csv") objectDB[2] = parse_object_file_into_db(parentLSMFilePath+"_tiles/objects/C"+str(channel)+".objects.keep.restitched.csv") objectDB[3] = parse_object_file_into_db(parentLSMFilePath+"_tiles/objects/C"+str(channel)+".objects.keep.unique.csv") ## Converts object global coordinates to rescaled coordinates for i in range(len(objectDB)): for j in range(len(objectDB[i])): rescaledTup = [objectDB[i][j][27]/scale_info[0],objectDB[i][j][28]/scale_info[0],objectDB[i][j][29],objectDB[i][j][30]/scale_info[0],objectDB[i][j][31]/scale_info[0],objectDB[i][j][32]]
################################################### # SETUP imTitles = WindowManager.getImageTitles() nTitles = len(imTitles) ## DIALOG d = GenericDialog("Measure") d.addChoice("Mask", imTitles, "-") d.addChoice("470 image", imTitles, "-") d.addChoice("410 image", imTitles, "-") d.addRadioButtonGroup("Binning", ["4x4", "2x2"], 1, 2, "4x4") d.showDialog() imgMask = WindowManager.getImage(d.getNextChoice()) img470 = WindowManager.getImage(d.getNextChoice()) img410 = WindowManager.getImage(d.getNextChoice()) binning = d.getNextRadioButton() PARENT_DIR = img410.getOriginalFileInfo().directory # setup data collection object dataTable = ResultsTable() ################################################## # INITIAL MEASUREMENTS table = ResultsTable() roiManager = RoiManager(True) # Boolean => Don't Display PA.setRoiManager(roiManager)
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 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 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")
else: # List column headers table = tableWindow.getResultsTable() headers = table.getHeadings() # Generate dialog with dropdown for column selection dialog = GenericDialog("PieChart from table column") dialog.addChoice("Data column", headers, headers[0]) dialog.addMessage( """Hover the mouse over the plot to view absolute and relative (%) values\n Right-click to set colors, export to PNG...\n Note: BarCharts usually provide better distinction than PieCharts for sectors with similar sizes (see Help).""" ) dialog.addHelp(r"https://www.data-to-viz.com/caveat/pie.html") dialog.showDialog() # Generate PieChart with data column if dialog.wasOKed(): # Get the data column as string selectedHeader = dialog.getNextChoice() column = table.getColumnAsVariables(selectedHeader) columnString = [str(item)[1:-1] for item in column] # [1:-1] to remove the "" # Make the PieChart for this data column if columnString: chart = PieChart(selectedHeader, columnString) chart.showFrame("PieChart")
from ij.gui import WaitForUserDialog from ij.gui import GenericDialog from ij.plugin.frame import RoiManager from ij.plugin.filter import ParticleAnalyzer from ij.plugin import ChannelSplitter # Set Threshold mode thresholdMode = False gd = GenericDialog("Set Threshold Mode") gd.addChoice("Would you like to enable thresholding mode?", ["No, run the normal macro", "Yes, enable thresholding mode"], "No") gd.showDialog() if gd.getNextChoice() == "Yes, enable thresholding mode": thresholdMode = True gd = GenericDialog("Set Thresholds") gd.addStringField("Lower bound for Red", "90") gd.addStringField("Lower bound for Green", "90") gd.addStringField("Lower bound for Blue", "100") gd.showDialog() thresholds = {} thresholds["Red"] = int(gd.getNextString() ) thresholds["Green"] = int(gd.getNextString() ) thresholds["Blue"] = int(gd.getNextString())
import time # Set Threshold mode thresholdMode = False colors2= ["Red" ,"Green" ,"Blue"] thresholds = {} gd = GenericDialog("Set Threshold Mode") gd.addChoice("Would you like to enable thresholding mode?", ["No, run the normal macro", "Yes, enable thresholding mode"], "No") gd.showDialog() if gd.getNextChoice() == "Yes, enable thresholding mode": thresholdMode = True if thresholdMode == False: gd = GenericDialog("Set Thresholds") gd.addStringField("Lower bound for Red", "90") gd.addStringField("Lower bound for Green", "100") gd.addStringField("Lower bound for Blue", "100") gd.showDialog() thresholds["Red"] = int(gd.getNextString()); thresholds["Green"] = int(gd.getNextString()); thresholds["Blue"] = int(gd.getNextString()); gd = GenericDialog("Other Thresholds.") gd.addMessage("Adjust after you have determined if new thresholds are needed.")
dc = DirectoryChooser("Select an output directory") outputDirectory = dc.getDirectory() for image in os.listdir(inputDirectory): print(image) if "stack" in image: imp = IJ.openImage(inputDirectory + "/" + image) imp2 = IJ.openImage(inputDirectory + "/" + image.replace("stack", "montage")) imp.show() imp2.show() gd = GenericDialog("?") gd.addChoice("Would you like to adjust this one?", ["No", "Yes"], "No") gd.showDialog() if gd.getNextChoice() == "Yes": imp2.close() IJ.run("Brightness/Contrast...") WaitForUserDialog("Title", "Adjust intensities").show() IJ.run("Stack to Images", "") IJ.run(imp, "Merge Channels...", "c2=Green c3=Blue c6=Magenta c7=Yellow create keep") imp = WindowManager.getCurrentImage() IJ.run(imp, "RGB Color", "") IJ.run(imp, "Images to Stack", "name=Stack title=[] use") #WaitForUserDialog("Title", "Now you should have a stack check it out ").show() imp = WindowManager.getCurrentImage() # the Stack imp.show() IJ.setForegroundColor(255, 255, 255) IJ.run(
from ij.process import ImageConverter from ij.gui import WaitForUserDialog from ij.gui import GenericDialog from ij.plugin.frame import RoiManager from ij.plugin.filter import ParticleAnalyzer # Set Threshold mode thresholdMode = False gd = GenericDialog("Set Threshold Mode") gd.addChoice("Would you like to enable thresholding mode?", ["No, run the normal macro", "Yes, enable thresholding mode"], "No") gd.showDialog() if gd.getNextChoice() == "Yes, enable thresholding mode": thresholdMode = True # Set watershed watershedMode = False gd = GenericDialog("Set Watershed Mode") gd.addChoice("Would you like to enable watershedding?", ["No, do not watershed", "Yes, enable watershed"], "No") gd.showDialog() if gd.getNextChoice() == "Yes, enable watershed": watershedMode = True # Set default thresholds: # round_threshold is the minimum roundness a roi must have to be considered an organoid for the isOrganoid column