def getChannels(subFolder): gd = GenericDialog("Channel Options") gd.addMessage("Name the markers associated with these subfolder:") gd.addMessage(subFolder) gd.addMessage("(Leave empty to ignore)") gd.addMessage("") gd.addStringField("Channel d0:", "Dapi") gd.addStringField("Channel d1:", "MAP2") gd.addStringField("Channel d2:", "") gd.addStringField("Channel d3:", "") gd.addMessage("") gd.showDialog() channelNames = [] channelNames.append([gd.getNextString(), 0]) channelNames.append([gd.getNextString(), 1]) channelNames.append([gd.getNextString(), 2]) channelNames.append([gd.getNextString(), 3]) channels = [] for i,v in enumerate(channelNames): if v[0] != "": channels.append(v) if gd.wasCanceled(): print "User canceled dialog!" return return channels
def user_input(): """ Takes user input on experiment parameters and stimulation applications... """ User_Input_List = [] Stim_List = [] # Creates dialog boxes proportionally to number of stimulations, type and duration. if Stim_num >= 1: gd = GenericDialog("Stimulation applications") for stim in range(0, Stim_num, 1): gd.addStringField("Stimulation type "+str(stim+1)+":", "cLTP") gd.addNumericField("Stimulation start:", stim*2, 2) gd.addNumericField("Stimulation end:", (stim+1)*2, 2) gd.showDialog() # Lists the different stimulations. for stim in range(0, Stim_num, 1): Type_Stim = gd.getNextString() Start_Stim = gd.getNextNumber() End_Stim = gd.getNextNumber() Stim_List.append([Type_Stim, float(Start_Stim), float(End_Stim)]) User_Input_List.extend(Stim_List) # Creates a dictionary of all user inputs. User_Input_Dict = {'Parameters': User_Input_List[0]} for stim in range(1, Stim_num, 1): User_Input_Dict['Stimulation '+str(stim)] = User_Input_List[stim] # Dumps dict to JSON. User_Input_Dict_JSON = (json.dumps(User_Input_Dict)) return User_Input_Dict, User_Input_Dict_JSON, Stim_List
def split_and_save(imp): base_title = imp.getShortTitle() base_dir = imp.getOriginalFileInfo().directory d = GenericDialog("Split Stacks") d.addMessage("Indicate the channels in your image stack, separated by commas") d.addMessage("Add the channels *in the order that you took the images*") d.addMessage("For example, \"TL, 410, 470, 410, 470\"") d.addStringField("Channels", "TL, 470, 410", 40) d.showDialog() # exit if cancelled if d.wasCanceled(): return None channels = number_duplicate_channels([x.strip() for x in d.getNextString().split(',')]) # Check that the number of images in stack is divisible by the number of channels # If not, quit. Else keep going if (imp.getNSlices() % len(channels) != 0): IJ.error("Invalid Channel Specification", "The number of slices (%d) is not divisible by the number of channels (%d). Exiting." % (imp.getNSlices(), len(channels))) return None imp.show() IJ.run("Deinterleave", "how=%d" % len(channels)) for i, img_id in enumerate(WindowManager.getIDList()): channel_i = WindowManager.getImage(img_id) channel_i.setTitle(base_title + "_" + channels[i]) IJ.saveAs(channel_i, "tif", base_dir + channel_i.getTitle()) IJ.showMessage("Saved image stacks as separate channels in %s" % base_dir)
def get_info(): srcDir = IJ.getDirectory("Input_Directory") if not srcDir: print("No input directory selected") return dstDir = IJ.getDirectory("Output_Directory") if not dstDir: print("No output directory selected") return gd = GenericDialog("Process Folder") gd.addStringField("File_extension", ".lif") gd.addStringField("File_name_contains", "") gd.addCheckbox("Keep directory structure when saving", True) gd.showDialog() if gd.wasCanceled(): return ext = gd.getNextString() containString = gd.getNextString() keepDirectories = gd.getNextBoolean() for root, directories, filenames in os.walk(srcDir): for filename in filenames: # Check for file extension if not filename.endswith(ext): continue # Check for file name pattern if containString not in filename: continue print(srcDir) print(filename) process(srcDir, dstDir, root, filename, keepDirectories)
def getName(text, defaultName = ''): gd = GenericDialog(text) gd.addStringField(text, defaultName) gd.showDialog() if gd.wasCanceled(): print 'User canceled dialog!' return return gd.getNextString()
def get_results_filename(): '''Prompt the user to suggest name of the output file.''' dialog = GenericDialog('Output results file') dialog.addStringField('Choose name without extension:', 'results') dialog.showDialog() name = dialog.getNextString() if dialog.wasCanceled(): return None #TODO Check if file exists before and try again? return name + '.csv'
def getChannels(subFolder): gd = GenericDialog("Channel Options") gd.addMessage("Name the markers associated with this directory:") gd.addMessage(inputDirectory + subFolder) gd.addMessage("(Leave empty to ignore)") gd.addMessage("") gd.addStringField("Channel ch00:", "Dapi") gd.addStringField("Channel ch01:", "pSYN") gd.addStringField("Channel ch02:", "MAP2") gd.addStringField("Channel ch03:", "SYN") gd.addMessage("") gd.addStringField("What would you like the output file to be named:", "output") gd.showDialog() channelNames = [] channelNames.append([gd.getNextString(), 0]) channelNames.append([gd.getNextString(), 1]) channelNames.append([gd.getNextString(), 2]) channelNames.append([gd.getNextString(), 3]) outputName = gd.getNextString() channels = [] for i, v in enumerate(channelNames): if v[0] != "": channels.append(v) if gd.wasCanceled(): print "User canceled dialog!" return return channels, outputName
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 inputScale(self): gd=GenericDialog("Scale ROI") gd.addStringField("X Scale:",str(self.xScale)) gd.addStringField("Y Scale:",str(self.yScale)) gd.addStringField("Scale X to pixel:",str(self.impXpixel)) gd.addStringField("Scale Y to pixel:",str(self.impYpixel)) fields=gd.getStringFields() self.XscaleField,self.YscaleField=fields[0],fields[1] self.toXfield,self.toYfield=fields[2],fields[3] self.XscaleField.addTextListener(self) self.YscaleField.addTextListener(self) self.toXfield.addTextListener(self) self.toYfield.addTextListener(self) gd.showDialog() if gd.wasOKed(): return(self.xScale,self.yScale) else: return(1.0,1.0)
def findclearcell_run(): inDir = IJ.getDirectory("Input directory") if not inDir: return gd = GenericDialog("Process Folder") gd.addStringField("File extension", ".oir") gd.addStringField("File name starts with (the date)", "") gd.showDialog() if gd.wasCanceled(): return ext = gd.getNextString() containString = gd.getNextString() for root, directories, filenames in os.walk(inDir): for fileName in filenames: if not fileName.endswith(ext): continue if containString not in fileName: continue print findclearcell(inDir, root, fileName)
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 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()
def main(): properties = ImageProperties(imp) # Create a GenericDialog to configure renaming: gd = GenericDialog('Gatan Reamer') gd.addMessage('Modifying: %s' % (imp.getTitle(),)) gd.addMessage('Recorded: %s' % (properties.date.toString(),)) gd.addNumericField('Exposure time', properties.exposure, 4, field_width, 's') gd.addNumericField('Magnification:', properties.magnification, 0, field_width, 'x') mag_units = ('kx', 'x') gd.addChoice('Magnification unit:', mag_units, mag_units[0]) gd.addMessage('The actual magnification is %.2f times larger.' % (properties.mag_factor,)) gd.addCheckbox('Use actual magnification:', False) gd.addMessage('') gd.addNumericField('Energy loss:', properties.energyloss, 1, field_width, 'eV') gd.addStringField('Date:', properties.date_string, field_width) gd.addStringField('original name:', properties.name, field_width_long) gd.addStringField('Filename format', default_format_str, field_width_long) gd.showDialog() if not gd.wasCanceled(): # Edit the properties to consiter user choices: properties.exposure = gd.getNextNumber() mag = gd.getNextNumber() properties.mag_unit = gd.getNextChoice() if gd.getNextBoolean(): properties.calc_mag(mag) properties.energyloss = gd.getNextNumber() properties.date_string = gd.getNextString() properties.name = gd.getNextString() format_str = gd.getNextString() # Chenge the title: imp.setTitle(format_str % properties.to_dict())
def setupDialog(imp): gd = GenericDialog("Collective migration buddy options") gd.addMessage("Collective migration buddy 2.0, you are analyzing: " + imp.getTitle()) calibration = imp.getCalibration() if (calibration.frameInterval > 0): default_interval = calibration.frameInterval default_timeunit = calibration.getTimeUnit() else: default_interval = 8 default_timeunit = "min" gd.addNumericField("Frame interval:", default_interval, 2) # show 2 decimals gd.addCheckbox("Do you want to use a gliding window?", True) gd.addCheckbox( "Project hyperStack? (defaluts to projecting current channel only)", False) gd.addStringField("time unit", default_timeunit, 3) gd.addSlider("Start compacting at frame:", 1, imp.getNFrames(), 1) gd.addSlider("Stop compacting at frame:", 1, imp.getNFrames(), imp.getNFrames()) gd.addNumericField("Number of frames to project in to one:", 3, 0) # show 0 decimals gd.addChoice('Method to use for frame projection:', methods_as_strings, methods_as_strings[5]) gd.showDialog() if gd.wasCanceled(): IJ.log("User canceled dialog!") return return gd
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 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";
name = imp.getTitle()[0:2] if not name.isdigit(): name = imp.getTitle()[0:1] #name = int(''.join(filter(str.isdigit, name))) IJ.run("Select All") IJ.run("Duplicate...", "check and close") newimp = IJ.getImage() rm.runCommand(newimp, "Show All") if rm.getCount() > 1: rm.setSelectedIndexes(range(rm.getCount())) rm.runCommand(newimp, "Combine") else: rm.select(newimp, 0) IJ.run("Make Inverse") IJ.run("Cut") gd = GenericDialog("suffix") gd.addStringField("suffix:", "") gd.showDialog() suffix = gd.getNextString() #ync = YesNoCancelDialog(None, "intensity (yes) or coverage (no or cancel)", "intensity (yes) or coverage (no or cancel)"); #if ync.yesPressed(): IJ.saveAs("Tiff", path + "\\prepared\\" + name + suffix + ".tif") #rm.runCommand("Delete") #else: #IJ.saveAs("Tiff", path + "\\coverage\\" + name + suffix + ".tif"); #IJ.saveAs("Tiff", path + "\\MTs\\prepared\\" + name + suffix + ".tif"); #IJ.run("Undo"); #ij.RUN("mAKE iNVERSE"); #ij.RUN("cUT"); #ij.SAVEaS("tIFF", PATH + "PREPARED\\" + NAME + "P.TIF"); #rm.runCommand("Save", path + "\\MTs\\prepared\\" + name + suffix + ".zip")
def run(): types = ['oneDay','oneMouse','oneFile','oneMonth','OneFolder','mapManager'] gd = GenericDialog('Define Source Options') #gd.addMessage('Choose the Source type:') gd.addChoice('Source Type:',types,types[0]) gd.showDialog() if gd.wasCanceled(): bPrintLog('user cancel the plugin',1) return 0 else: srcType = gd.getNextChoiceIndex() #run one day if srcType == 0: dayFolder = DirectoryChooser('Please Choose A Directory Of .tif Files').getDirectory() if not os.path.isdir(dayFolder): bPrintLog('\nERROR: runOneDay() did not find folder: ' + dayFolder + '\n',0) return 0 overWriteDate(dayFolder) #run one mouse if srcType == 1: mouseFolder = DirectoryChooser('Please Choose A Mouse Directory Of .tif Files').getDirectory() if not mouseFolder: exit(1) overWriteMouse(mouseFolder) #run one file if srcType == 2: od = OpenDialog("Choose a convoluted tif file to overwrite", None) srcDirectory = od.getDirectory() srcFile = od.getFileName() if srcFile != None: fileFullPath = os.path.join(srcDirectory,srcFile) convert32to16(fileFullPath) #run one month if srcType == 3: monthFolder = DirectoryChooser('Please Choose A MONTH Directory Of .tif Files').getDirectory() if not os.path.isdir(monthFolder): bPrintLog('\nERROR: runOneMonth() did not find folder: ' + monthFolder + '\n',0) return 0 runOneMonth(monthFolder) #run one Folder if srcType == 4: srcFolder = DirectoryChooser('Please Choose A folder Of .tif Files').getDirectory() if not os.path.isdir(srcFolder): bPrintLog('\nERROR: runOneFolder() did not find folder: ' + srcFolder + '\n',0) return 0 runOneFolder(srcFolder) if srcType == 5: #align centain map's raw folder mapPath = 'G:/ZY/MapManager3' #mapNames = raw_input('type maps initials seperated with ,: ').split(',') #raw_input does not work here #mapNames = tuple(mapNames) mapNames = "F58,F59" #preset #get map names gd = GenericDialog('Choose maps for alignment') gd.addStringField("maps root path",mapPath,50) gd.addStringField("maps name initials sep = ','(empty for all)",mapNames,50) gd.showDialog() if gd.wasCanceled(): bPrintLog('user cancel the plugin',0) return 0 mapPath = gd.getNextString() mapNames = tuple(gd.getNextString().split(',')) mapFolders = [f for f in os.listdir(mapPath) if f.startswith(mapNames) and os.path.isdir(os.path.join(mapPath,f))] if len(mapFolders) == 0: bPrintLog('\nERROR: no map folder found',0) return 0 bPrintLog('Map Folder number: ' + str(len(mapFolders)),0) #put option here so we do not have to click for each folder sourceFolders= [mapPath + '/' + mapFolder + '/raw/raw_userRaw' for mapFolder in mapFolders] for srcFolder in sourceFolders: runOneFolder(srcFolder)
def run(): types = [ 'oneDay', 'oneMouse', 'oneFile', 'oneMonth', 'OneFolder', 'mapManager' ] gd = GenericDialog('Define Source Options') #gd.addMessage('Choose the Source type:') gd.addChoice('Source Type:', types, types[0]) gd.showDialog() if gd.wasCanceled(): bPrintLog('user cancel the plugin', 1) return 0 else: srcType = gd.getNextChoiceIndex() #run one day if srcType == 0: dayFolder = DirectoryChooser( 'Please Choose A Directory Of .tif Files').getDirectory() if not os.path.isdir(dayFolder): bPrintLog( '\nERROR: runOneDay() did not find folder: ' + dayFolder + '\n', 0) return 0 overWriteDate(dayFolder) #run one mouse if srcType == 1: mouseFolder = DirectoryChooser( 'Please Choose A Mouse Directory Of .tif Files').getDirectory( ) if not mouseFolder: exit(1) overWriteMouse(mouseFolder) #run one file if srcType == 2: od = OpenDialog("Choose a convoluted tif file to overwrite", None) srcDirectory = od.getDirectory() srcFile = od.getFileName() if srcFile != None: fileFullPath = os.path.join(srcDirectory, srcFile) convert32to16(fileFullPath) #run one month if srcType == 3: monthFolder = DirectoryChooser( 'Please Choose A MONTH Directory Of .tif Files').getDirectory( ) if not os.path.isdir(monthFolder): bPrintLog( '\nERROR: runOneMonth() did not find folder: ' + monthFolder + '\n', 0) return 0 runOneMonth(monthFolder) #run one Folder if srcType == 4: srcFolder = DirectoryChooser( 'Please Choose A folder Of .tif Files').getDirectory() if not os.path.isdir(srcFolder): bPrintLog( '\nERROR: runOneFolder() did not find folder: ' + srcFolder + '\n', 0) return 0 runOneFolder(srcFolder) if srcType == 5: #align centain map's raw folder mapPath = 'G:/ZY/MapManager3' #mapNames = raw_input('type maps initials seperated with ,: ').split(',') #raw_input does not work here #mapNames = tuple(mapNames) mapNames = "F58,F59" #preset #get map names gd = GenericDialog('Choose maps for alignment') gd.addStringField("maps root path", mapPath, 50) gd.addStringField("maps name initials sep = ','(empty for all)", mapNames, 50) gd.showDialog() if gd.wasCanceled(): bPrintLog('user cancel the plugin', 0) return 0 mapPath = gd.getNextString() mapNames = tuple(gd.getNextString().split(',')) mapFolders = [ f for f in os.listdir(mapPath) if f.startswith(mapNames) and os.path.isdir(os.path.join(mapPath, f)) ] if len(mapFolders) == 0: bPrintLog('\nERROR: no map folder found', 0) return 0 bPrintLog('Map Folder number: ' + str(len(mapFolders)), 0) #put option here so we do not have to click for each folder sourceFolders = [ mapPath + '/' + mapFolder + '/raw/raw_userRaw' for mapFolder in mapFolders ] for srcFolder in sourceFolders: runOneFolder(srcFolder)
gd.showDialog() choice = gd.getNextChoice() if choice == "10X Evos": pix_width = 0.8777017 pix_height = 0.8777017 if choice == "4X Evos": pix_width = 2.1546047 pix_height = 2.1546047 if choice == "Other": gd = GenericDialog("Dimension Options") gd.addMessage("Conversion from pixels to uM :Calculate for your objective and enter below") gd.addStringField("Pixel Width:", "0.8777017") gd.addStringField("Pixel Height:", "0.8777017") gd.showDialog() pix_width = gd.getNextString() pix_height = gd.getNextString() # Get input and output directories with GUI dc = DirectoryChooser("Choose an input directory") inputDirectory = dc.getDirectory() dc = DirectoryChooser("Choose an output directory") outputDirectory = dc.getDirectory()
"No") gd.addMessage( "Watershed will NOT be run in threshold mode and WILL BE RUN in macro mode." ) gd.showDialog() if gd.getNextChoice() == "Yes, enable thresholding mode": thresholdMode = True # Set default thresholds: # round_threshold is the minimum roundness a roi must have to be considered an organoid for the isOrganoid column # area_threshold is the minimum area a roi must have to be considered an organoid for the isorganoid column # minimum_size is the minimum area to be considered an ROI gd = GenericDialog("Other Thresholds.") gd.addMessage("Ajust after you have determined if new thresholds are needed.") gd.addStringField("Round threshold", "0.62") gd.addStringField("Area Threshold", "50000") gd.addStringField("Minimum Size", "3000") gd.showDialog() round_threshold = float(gd.getNextString()) area_threshold = float(gd.getNextString()) minimum_size = float(gd.getNextString()) #set pix_width and pix_height to real dimensions per pixel gd = GenericDialog("Dimension Options") gd.addMessage( "Conversion from pixles to uM :Evos 10X pixle width/height = 0.8777017 uM") gd.addMessage( "Conversion from pixles to uM :Evos 4X pixle width/height = 2.1546047 uM")
def run(): types = ['oneDay', 'oneFolder', 'oneFile', 'mapmaneger', 'test'] gd = GenericDialog('Define Source Options') #gd.addMessage('Choose the Source type:') gd.addChoice('Source Type:', types, types[0]) gd.showDialog() if gd.wasCanceled(): print 'user cancel the plugin' return 0 else: srcType = gd.getNextChoiceIndex() #run one day if srcType == 0: dayFolder = DirectoryChooser( 'Please Choose A Directory Of .tif Files').getDirectory() if not os.path.isdir(dayFolder): bab.bPrintLog( '\nERROR: runOneDay() did not find folder: ' + dayFolder + '\n', 0) return 0 dirNames = [ file for file in os.listdir(dayFolder) if os.path.isdir(os.path.join(dayFolder, file)) ] numDirs = len(dirNames) bab.bPrintLog('dayFolder is:' + dayFolder, 0) bab.bPrintLog('Number of subFolders: ' + str(numDirs), 1) #put option here so we do not have to click for each folder if bab.Options(dayFolder + dirNames[0] + '/'): for dirName in dirNames: #sourceFolder = os.path.join(dayFolder, dirName) # did not add '/' to the end sourceFolder = dayFolder + '/' + dirName + '/' bab.runOneFolder(sourceFolder) #run one folder if srcType == 1: sourceFolder = DirectoryChooser( 'Please Choose A Directory Of .tif Files').getDirectory() if not sourceFolder: exit(1) if bab.Options(sourceFolder): bab.runOneFolder(sourceFolder) #run one file if srcType == 2: od = OpenDialog("Choose image file", None) srcDirectory = od.getDirectory() srcFile = od.getFileName() if srcFile != None and bab.Options(srcDirectory): bab.runOneFile(srcDirectory + srcFile) if srcType == 3: #align centain map's raw folder mapPath = 'G:/ZY/MapManager3' #mapNames = raw_input('type maps initials seperated with ,: ').split(',') #raw_input does not work here #mapNames = tuple(mapNames) mapNames = "F58,F59" #preset #get map names gd = GenericDialog('Choose maps for alignment') gd.addStringField("maps root path", mapPath, 50) gd.addStringField("maps name initials sep = ','", mapNames, 50) gd.showDialog() if gd.wasCanceled(): bab.bPrintLog('user cancel the plugin', 0) return 0 mapPath = gd.getNextString() mapNames = tuple(gd.getNextString().split(',')) mapFolders = [ f for f in os.listdir(mapPath) if f.startswith(mapNames) and os.path.isdir(os.path.join(mapPath, f)) ] if len(mapFolders) == 0: bab.bPrintLog('\nERROR: no map folder found', 0) return 0 bab.bPrintLog('Map Folder number: ' + str(len(mapFolders)), 0) #put option here so we do not have to click for each folder sourceFolders = [ mapPath + '/' + mapFolder + '/raw/' for mapFolder in mapFolders ] if bab.Options(sourceFolders[0]): for sourceFolder in sourceFolders: bab.runOneFolder(sourceFolder) if srcType == 4: #for test gd = GenericDialog('Choose maps') gd.addStringField('maps name initials', 'F58,F59') gd.showDialog() maps = gd.getNextString().split(',') maps = tuple(maps) bab.bPrintLog(maps[0], 0)
def run(): types = ['oneDay','oneFolder','oneFile','mapmaneger','test'] gd = GenericDialog('Define Source Options') #gd.addMessage('Choose the Source type:') gd.addChoice('Source Type:',types,types[0]) gd.showDialog() if gd.wasCanceled(): print 'user cancel the plugin' return 0 else: srcType = gd.getNextChoiceIndex() #run one day if srcType == 0: dayFolder = DirectoryChooser('Please Choose A Directory Of .tif Files').getDirectory() if not os.path.isdir(dayFolder): bab.bPrintLog('\nERROR: runOneDay() did not find folder: ' + dayFolder + '\n',0) return 0 dirNames = [file for file in os.listdir(dayFolder) if os.path.isdir(os.path.join(dayFolder,file))] numDirs = len(dirNames) bab.bPrintLog('dayFolder is:' + dayFolder,0) bab.bPrintLog('Number of subFolders: ' + str(numDirs),1) #put option here so we do not have to click for each folder if bab.Options(dayFolder + dirNames[0] + '/'): for dirName in dirNames: #sourceFolder = os.path.join(dayFolder, dirName) # did not add '/' to the end sourceFolder = dayFolder + '/' + dirName + '/' bab.runOneFolder(sourceFolder) #run one folder if srcType == 1: sourceFolder = DirectoryChooser('Please Choose A Directory Of .tif Files').getDirectory() if not sourceFolder: exit(1) if bab.Options(sourceFolder): bab.runOneFolder(sourceFolder) #run one file if srcType == 2: od = OpenDialog("Choose image file", None) srcDirectory = od.getDirectory() srcFile = od.getFileName() if srcFile != None and bab.Options(srcDirectory): bab.runOneFile(srcDirectory + srcFile) if srcType == 3: #align centain map's raw folder mapPath = 'G:/ZY/MapManager3' #mapNames = raw_input('type maps initials seperated with ,: ').split(',') #raw_input does not work here #mapNames = tuple(mapNames) mapNames = "F58,F59" #preset #get map names gd = GenericDialog('Choose maps for alignment') gd.addStringField("maps root path",mapPath,50) gd.addStringField("maps name initials sep = ','",mapNames,50) gd.showDialog() if gd.wasCanceled(): bab.bPrintLog('user cancel the plugin',0) return 0 mapPath = gd.getNextString() mapNames = tuple(gd.getNextString().split(',')) mapFolders = [f for f in os.listdir(mapPath) if f.startswith(mapNames) and os.path.isdir(os.path.join(mapPath,f))] if len(mapFolders) == 0: bab.bPrintLog('\nERROR: no map folder found',0) return 0 bab.bPrintLog('Map Folder number: ' + str(len(mapFolders)),0) #put option here so we do not have to click for each folder sourceFolders= [mapPath + '/' + mapFolder + '/raw/' for mapFolder in mapFolders] if bab.Options(sourceFolders[0]): for sourceFolder in sourceFolders: bab.runOneFolder(sourceFolder) if srcType == 4: #for test gd = GenericDialog('Choose maps') gd.addStringField('maps name initials','F58,F59') gd.showDialog() maps = gd.getNextString().split(',') maps = tuple(maps) bab.bPrintLog(maps[0],0)
import time import logging outDirChoices = ["New Directory, no subfolders", "New Directory, keep input subfolders", "Within (subfolders of) input directory"] thresholdChoices = ["Otsu, white objects, stack, histogram of each slice", "Otsu, white objects, stack, stack histogram", "Otsu, white objects, try both methods"] overwriteChoices = ["NO overwrite existing files", "Overwrite existing files"] mipChoices = ["yes: tiff", "yes: jpg"] overwriteList = [] startTime = time.time() imageCount = 0 gd = GenericDialog("Set binarization.py Options") gd.addStringField("String to identify your input images", "_deconv") gd.addRadioButtonGroup("Output", outDirChoices, 3, 1, outDirChoices[0]) gd.addRadioButtonGroup("Threshold Settings", thresholdChoices, 3, 1, thresholdChoices[0]) gd.addRadioButtonGroup("Overwrite", overwriteChoices, 2, 1, overwriteChoices[0]) gd.addCheckboxGroup(2, 1, mipChoices, [False, False], ["Do you want maximum intensity projections of your images?"]) gd.showDialog() if gd.wasCanceled(): exit() fileID = gd.getNextString() outDirPref = gd.getNextRadioButton() thresholdPref = gd.getNextRadioButton() overwritePref = gd.getNextRadioButton() mipPrefTIFF = gd.getNextBoolean() mipPrefJPG = gd.getNextBoolean() IJ.redirectErrorMessages(True)
for i in range(len(wList)): currImage = WindowManager.getImage(wList[i]) currImage.close() returnVal = 1 else: IJ.log("skipped") returnVal = 2 return returnVal dc = DirectoryChooser("Choose root directory") rootPath = dc.getDirectory() if rootPath is not None: gd = GenericDialog("Batch mode options...") gd.addStringField("Filename extension","lsm",6) gd.showDialog() if (gd.wasOKed()): extension = gd.getNextString() for root, dirs, files in os.walk(rootPath): LSMfiles = filter(lambda x: check_if_filetype(x,extension),files) if len(LSMfiles)>0: LSMpaths = map(lambda x: generate_path(x,root),LSMfiles) explodeStatuses = map(run_explode,LSMpaths) resizePaths = map(get_first_in_tuple,filter(filter_by_return_status,map(lambda x,y:(x,y),LSMpaths,explodeStatuses))) if len(resizePaths)>0: resizeStatuses = map(run_resize,resizePaths) stitchPaths = map(get_first_in_tuple,filter(filter_by_return_status,map(lambda x,y:(x,y),resizePaths,resizeStatuses))) if len(stitchPaths)>0: stitchStatuses = map(run_stitch,stitchPaths) combinePaths = map(get_first_in_tuple,filter(filter_by_return_status,map(lambda x,y:(x,y),stitchPaths,stitchStatuses)))
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 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
if __name__ == "__main__": t0 = time.time() print t0 - t0 imgSource = IJ.getImage() root = '/tier2/saalfeld/hanslovskyp/shan/thickness/' c = imgSource.getWidth()/2 height = imgSource.getHeight() dialog = GenericDialog( "Overlapping thickness estimation" ) dialog.addStringField( "Root directory for storing results", root ) dialog.addCheckbox( "Render matrix to image at each iteration.", False ) dialog.addNumericField( "Start.", 0, 0 ) dialog.addNumericField( "Stop.", height, 0 ) dialog.addNumericField( "Interval size.", 1000, 0 ) dialog.addNumericField( "Overlap.", imgSource.getWidth()/2, 0 ) dialog.addNumericField( "Range.", c, 0 ) dialog.showDialog() if dialog.wasCanceled(): raise Exception( "dialog was canceled" ) root = dialog.getNextString() doRender = dialog.getNextBoolean() start = dialog.getNextNumber()
def getChannels(subFolder): gd = GenericDialog("Channel Options") gd.addStringField("Brain Region:", "") gd.addMessage("Name the markers associated with this directory:") gd.addMessage(inputDirectory + subFolder) gd.addMessage("(Leave empty to ignore)") gd.addMessage("") gd.addStringField("Channel 1:", "HEMO") gd.addStringField("Minimum size for Channel 1:", "20") gd.addStringField("Max size for Channel 1:", "500") gd.addMessage("") gd.addStringField("Channel 2:", "DAB") gd.addStringField("Minimum size for Channel 2:", "30") gd.addStringField("Minimum size for Channel 2:", "500") # gd.addStringField("Channel 3:", "") gd.showDialog() channelNames = [] region = gd.getNextString() channelNames.append([gd.getNextString(), 0]) tooSmallHEMO = gd.getNextString() tooBigHEMO = gd.getNextString() channelNames.append([gd.getNextString(), 1]) tooSmallDAB = gd.getNextString() tooBigDAB = gd.getNextString() #channelNames.append([gd.getNextString(), 2]) channels = [] for i, v in enumerate(channelNames): if v[0] != "": channels.append(v) if gd.wasCanceled(): print "User canceled dialog!" return return region, tooSmallHEMO, tooSmallDAB, tooBigHEMO, tooBigDAB, channels
desktop = Desktop.getDesktop() uri = URI("https://colab.research.google.com/drive/1PRgFZnd0OtT6p61Ce2y0POEoKPNtTE5N#scrollTo=uU-B_7MwFohd") #test url desktop.browse(uri) session = None channel = None DIALOG = True if (DIALOG): # ----------------- DIALOG TO FILL GLOBAL PARAMETERS ----- gui = GenericDialog("Parameters") gui.addStringField("NGROK Server address :", "0.tcp.ngrok.io") gui.addStringField("PORT :", "") gui.showDialog() HOST = gui.getNextString() PORT = int(gui.getNextString()) gui = GenericDialogPlus("Parameters") gui.addFileField("Select a model file in Keras format (*.h5) : ", "") gui.showDialog() if gui.wasOKed(): LOCAL_MODEL_FILENAME = gui.getNextString() gui = GenericDialogPlus("Parameters") gui.addFileField("Select a python script file to upload on the server (*.py) : ", "") gui.showDialog() if gui.wasOKed():
for p in data[counter]: if '_' + channel2 + '_' in p: imp2 = IJ.openImage(i['path'] + '/' + p) IJ.setThreshold(imp2, lowth2, 255) IJ.run(imp2, "Create Selection", "") IJ.run(imp2, "Measure", "") counter += 1 IJ.renameResults(channel2) # User input directory directory = IJ.getDirectory("Input_directory") # Make dialog box, with channel, threshold and "subdirectory" inputs 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
from java.awt import Color from java.awt.event import TextListener from ij import IJ from ij import Menus from ij.gui import GenericDialog #commands = [c for c in ij.Menus.getCommands().keySet()] # Above, equivalent list as below: commands = Menus.getCommands().keySet().toArray() gd = GenericDialog('Command Launcher') gd.addStringField('Command: ', ''); prompt = gd.getStringFields().get(0) prompt.setForeground(Color.red) class TypeListener(TextListener): def textValueChanged(self, tvc): if prompt.getText() in commands: prompt.setForeground(Color.black) return prompt.setForeground(Color.red) # or loop: #for c in commands: # if c == text: # prompt.setForeground(Color.black) # return # #prompt.setForeground(Color.red) prompt.addTextListener(TypeListener()) gd.showDialog() if not gd.wasCanceled(): IJ.doCommand(gd.getNextString())
class Colortags: ''' This class handles persistence of the name of different color channels. It instantiates a GUI window to capture and show the color names in use. Other classes such as ColorMerger needs this to determine the color of the channel being processed. ''' def __init__(self): self.window = None self.tags = {} self.prefkeys = ["{0}.{1}".format(SUBKEY, name) for name in COLORS] self.userprefs = Prefs() self.load() while not self.tags: self.edit("Please set at least one colortag.\n\n") def load(self): ''' Tries to load IBPlib colortags from IJ prefs. ''' for i in range(7): storedtags = self.userprefs.getString(".{0}".format(self.prefkeys[i]), "") if not storedtags: continue trimmedtagslist = [t.strip() for t in storedtags.split(",")] self.tags.update({i:trimmedtagslist}) def edit(self, msg=""): ''' Opens the color tags dialog to update color tags ''' self.window = GenericDialog("ColorMerger - Edit color tags") self.window.addMessage("{0}Separate tags with a comma.\nBlank values will be ignored.".format(msg)) for i in range(7): try: self.window.addStringField(COLORS[i], ", ".join(self.tags[i]), 30) except KeyError: self.window.addStringField(COLORS[i], "", 30) self.window.setOKLabel("Save") self.window.showDialog() if self.window.wasOKed(): self.__savetags() self.load() def __validate(self): fields = self.window.getStringFields() newvalues = {} for i in range(len(fields)): txt = fields[i].getText() newvalues.update({i: txt.strip()}) return newvalues def __savetags(self): newvalues = self.__validate() for i, tags in newvalues.items(): key = self.prefkeys[i] self.userprefs.set(key, tags) self.userprefs.savePreferences()
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.") # Set default thresholds: # minimum_size is the minimum area to be considered an ROI
import time import logging outDirChoices = ["New Directory, no subfolders", "New Directory, keep input subfolders", "Within (subfolders of) input directory"] overwriteChoices = ["NO overwrite existing files", "Overwrite existing files"] channelSubfolderChoices = ["yes", "no"] mipChoices = ["yes: tiff", "yes: jpg"] overwriteList = [] startTime = time.time() imageCount = 0 voxel_info = str() gd = GenericDialog("Set ToTiff Options") gd.addStringField("File extension to be processed", ".nd2") gd.addRadioButtonGroup("Output", outDirChoices, 3, 1, outDirChoices[0]) gd.addRadioButtonGroup("Overwrite", overwriteChoices, 2, 1, overwriteChoices[0]) gd.addRadioButtonGroup("Save channels in different subfolders", channelSubfolderChoices, 1, 1, channelSubfolderChoices[0]) gd.addCheckboxGroup(2, 1, mipChoices, [False, False], ["Do you want maximum intensity projections of your images?"]) gd.showDialog() if gd.wasCanceled(): exit() fileExt = gd.getNextString() outDirPref = gd.getNextRadioButton() overwritePref = gd.getNextRadioButton() channelSubfolderPref = gd.getNextRadioButton() mipPrefTIFF = gd.getNextBoolean() mipPrefJPG = gd.getNextBoolean()
[str(id), str(t), str(time), str(x), str(y)]) #writer2.writerow([str(sid), str(x), str(y), str(id), str(t)]) gd = GenericDialog("Tracking settings") gd.addNumericField("Pixel_calibration (micron)", 0.63, 0) gd.addNumericField("Time Frame (s)", 300, 1) gd.addNumericField("LINKING_MAX_DISTANCE (pixel)", 20, 1) gd.addNumericField("GAP_CLOSING_MAX_DISTANCE (pixel)", 20, 1) gd.addNumericField("MAX_FRAME_GAP", 1, 1) gd.addCheckbox("ALLOW_TRACK_SPLITTING", True) gd.addNumericField("SPLITTING_MAX_DISTANCE (pixel)", 20, 1) gd.addCheckbox("ALLOW_TRACK_MERGING", False) gd.addNumericField("MERGING_MAX_DISTANCE (pixel)", 20, 1) gd.addStringField("File_extension", ".tif") gd.addStringField("File_name_contains", "") gd.addCheckbox("Keep directory structure when saving", True) gd.addCheckbox("Show tracks", False) gd.showDialog() Pixel_calibration = gd.getNextNumber() Time_interval = gd.getNextNumber() LINKING_MAX_DISTANCE = gd.getNextNumber() GAP_CLOSING_MAX_DISTANCE = gd.getNextNumber() MAX_FRAME_GAP = int(gd.getNextNumber()) ALLOW_TRACK_SPLITTING = gd.getNextBoolean() SPLITTING_MAX_DISTANCE = gd.getNextNumber() ALLOW_TRACK_MERGING = gd.getNextBoolean() MERGING_MAX_DISTANCE = gd.getNextNumber() ext = gd.getNextString()
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("Name your image (write a 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+)')
roi = OvalRoi(new_x, new_y, radius*2, radius*2) imp.setRoi(roi) ER_mean = (selection_mean()) ER.append(ER_mean) IJ.run(imp, "Draw", "slice") try: with open(Quant) as infile: reader = csv.reader(infile) row_count = sum(1 for row in reader) cell_number = row_count except: cell_number = 1 gd = GenericDialog("Type cell number") gd.addStringField("Cell number", str(cell_number)) gd.showDialog() number = gd.getNextString() ER1 = ER[0] ER2 = ER[1] ER3 = ER[2] total_ER = sum(ER) average_ER = total_ER / 3 net_ER = average_ER - background try: net_golgi = average_max - background t_index = net_golgi / net_ER except: net_golgi = 'Pixels saturated in Transport Channel' t_index = 'Pixels saturated in Transport Channel'
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()) # Set default thresholds: # minimum_size is the minimum area to be considered an ROI
def run(): ### Default arguments two_sarcomere_size = 25 # determined by filter used. rotation_angle = 0.0 ### Get the image we'd like to work with. # Don't need to ask where to save the intermediate image since it'll just be saved in the matchedmyo folder anyway # may change this though. In case they want to keep that image around. this_img = WindowManager.getCurrentImage() if this_img == None: ud = WaitForUserDialog( "Please select the image you would like to analyze.") ud.show() this_img = WindowManager.getCurrentImage() img_name = this_img.getTitle() matchedmyo_path = "/home/AD/dfco222/scratchMarx/matchedmyo/" # this would be grabbed from the prompt gd = GenericDialog("Preprocessing Options") gd.addCheckbox("Automatic Resizing/Rotation", True) gd.addCheckbox("CLAHE", True) gd.addCheckbox("Normalization to Transverse Tubules", True) gd.showDialog() if gd.wasCanceled(): return auto_resize_rotate = gd.getNextBoolean() clahe = gd.getNextBoolean() normalize = gd.getNextBoolean() if auto_resize_rotate: # Clear selection so it takes FFT of full image rotation_angle = auto_resize_angle_measure(this_img, two_sarcomere_size) if clahe: clahe_args = "blocksize={} histogram=256 maximum=3 mask=*None* fast_(less_accurate)".format( two_sarcomere_size) IJ.run(this_img, "Enhance Local Contrast (CLAHE)", clahe_args) if normalize: # Ask the user to select a subsection of the image that looks healthy-ish. ud = WaitForUserDialog( "Please select a subsection exhibiting a measure of healthy TT structure using the Rectangle tool.\n" + " Only a single cell or several are needed.\n\n" + " Press 'OK' when finished.") ud.show() IJ.setTool("rectangle") # Duplicate the selected subsection. selection = this_img.crop() IJ.run(selection, "Duplicate...", "title=subsection.tif") # Grab the subsection image and rotate it. selection = WindowManager.getImage("subsection.tif") IJ.run( selection, "Rotate...", "angle={} grid=1 interpolation=Bicubic enlarge".format( rotation_angle)) # Ask the user to select a bounding box that contains only tubules # NOTE: Need to get rid of initial selection since it's the entire image and it's annoying to click out of IJ.setTool("rectangle") IJ.run(selection, "Select None", "") ud = WaitForUserDialog( "Select a subsection of the image that contains only tubules and no membrane." ) ud.show() # Grab the subsection ImagePlus selection = WindowManager.getCurrentImage() this_window = WindowManager.getActiveWindow() selection_small = selection.crop() IJ.run(selection, "Close", "") # NOTE: May not actually display this depending on how the macros work IJ.run(selection_small, "Duplicate...", "title=subsection_small.tif") # Smooth the selection using the single TT filter. # NOTE: It won't read in so we're just going to hard code it in since it's simple tt_filt_row = "0 0 0 1 1 1 1 1 1 0 0 0 0\n" tt_filt = "" for i in range(21): tt_filt += tt_filt_row IJ.run("Convolve...", "text1=[" + tt_filt + "] normalize") # Segment out the TTs from the 'gaps' using Gaussian Adaptive Thresholding. selection_small = WindowManager.getImage("subsection_small.tif") IJ.run(selection_small, "Duplicate...", "title=thresholded.tif") threshed = WindowManager.getImage("thresholded.tif") IJ.run(threshed, "Auto Local Threshold", "method=Bernsen radius=7 parameter_1=1 parameter_2=0 white") # Select the TTs from the thresholded image. IJ.run(threshed, "Create Selection", "") tt_selection = WindowManager.getImage("subsection_small.tif") IJ.selectWindow("thresholded.tif") IJ.selectWindow("subsection_small.tif") IJ.run(tt_selection, "Restore Selection", "") # Get TT intensity statistics. stat_options = IS.MEAN | IS.MIN_MAX | IS.STD_DEV stats = IS.getStatistics(tt_selection.getProcessor(), stat_options, selection_small.getCalibration()) # Calculate pixel ceiling intensity value based on heuristic. # TODO: Add a catch for data type overflow. pixel_ceiling = stats.mean + 3 * stats.stdDev print "px ceil:", pixel_ceiling # Invert selection to get inter-sarcomeric gap intensity statistics. IJ.run(tt_selection, "Make Inverse", "") stat_options = IS.MEAN | IS.MIN_MAX | IS.STD_DEV stats = IS.getStatistics(tt_selection.getProcessor(), stat_options, selection_small.getCalibration()) # Calculate pixel floor intensity value based on heuristic. pixel_floor = stats.mean - stats.stdDev # TODO: Add a catch for data type underflow. print "px floor:", pixel_floor # Threshold original image based on these values. IJ.selectWindow(this_img.getTitle()) IJ.run(this_img, "Select All", "") IJ.setMinAndMax(pixel_floor, pixel_ceiling) IJ.run(this_img, "Apply LUT", "") ## Ask if it is acceptable. gd = GenericDialog("Acceptable?") gd.addMessage( "If the preprocessed image is acceptable for analysis, hit 'OK' to being analysis.\n" + " If the image is unacceptable or an error occurred, hit 'Cancel'") gd.showDialog() if gd.wasCanceled(): return ## Save the preprocessed image. imp = IJ.getImage() fs = FileSaver(imp) img_save_dir = matchedmyo_path + "myoimages/" # actually get from user at some point img_file_path = img_save_dir + img_name[:-4] + "_preprocessed.tif" if os.path.exists(img_save_dir) and os.path.isdir(img_save_dir): print "Saving image as:", img_file_path if os.path.exists(img_file_path): # use dialog box to ask if they want to overwrite gd = GenericDialog("Overwrite?") gd.addMessage( "A file exists with the specified path, \"{}\". Would you like to overwrite it?" .format(img_file_path)) gd.enableYesNoCancel() gd.showDialog() if gd.wasCanceled(): return elif fs.saveAsTiff(img_file_path): print "Preprocessed image saved successfully at:", '"' + img_file_path + '"' else: print "Folder does not exist or is not a folder!" ### Create the YAML file containing the parameters for classification ## Ask user for YAML input gd = GenericDialog("YAML Input") gd.addStringField("imageName", img_file_path, 50) #gd.addStringField("maskName", "None") gd.addStringField("outputParams_fileRoot", img_file_path[:-4], 50) gd.addStringField("outputParams_fileType", "tif") gd.addNumericField("outputParams_dpi", 300, 0) gd.addCheckbox("outputParams_saveHitsArray", False) gd.addStringField("outputParams_csvFile", matchedmyo_path + "results/") gd.addCheckbox("TT Filtering", True) gd.addToSameRow() gd.addCheckbox("LT Filtering", True) gd.addToSameRow() gd.addCheckbox("TA Filtering", True) gd.addNumericField("scopeResolutions_x", 5.0, 3) gd.addToSameRow() gd.addNumericField("scopeResolutions_y", 5.0, 3) gd.addMessage("Enter in filter rotation angles separated by commas.") gd.addStringField("", "-25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25", 50) gd.addCheckbox("returnAngles", False) gd.addCheckbox("returnPastedFilter", True) gd.showDialog() if gd.wasCanceled(): return strings = [st.text for st in gd.getStringFields()] #if strings[1] == "None" or "": # strings[1] = None nums = [float(num.text) for num in gd.getNumericFields()] nums[0] = int(nums[0]) # Have to make sure the dpi variable is an integer checks = [str(bool(boo.state)) for boo in gd.getCheckboxes()] iter_argument = ','.join( [str(float(it) - rotation_angle) for it in strings[4].split(',')]) string_block = """imageName: {0[0]} outputParams: fileRoot: {0[1]} fileType: {0[2]} dpi: {1[0]} saveHitsArray: {2[0]} csvFile: {0[3]} preprocess: False filterTypes: TT: {2[1]} LT: {2[2]} TA: {2[3]} scopeResolutions: x: {1[1]} y: {1[2]} iters: [{3}] returnAngles: {2[4]} returnPastedFilter: {2[5]}""".format(strings, nums, checks, iter_argument) im_title = this_img.getTitle() with cd(matchedmyo_path): yaml_file_path = "./YAML_files/" + im_title[:-4] + ".yml" with open("./YAML_files/" + im_title[:-4] + ".yml", "w") as ym: ym.write(string_block) print "Wrote YAML file to:", matchedmyo_path + yaml_file_path[2:] ### Run the matchedmyo code on the preprocessed image with cd(matchedmyo_path): #os.chdir(matchedmyo_path) #subprocess.call(["python3", matchedmyo_path+"matchedmyo.py", "fullValidation"]) subprocess.call( ["python3", "matchedmyo.py", "run", "--yamlFile", yaml_file_path])
scoreField.requestFocusInWindow() # Get the grid files chooser = JFileChooser() chooser.setDialogTitle("Choose plate grids") chooser.setMultiSelectionEnabled(True) chooser.setCurrentDirectory( File(os.path.expanduser("~"))) chooser.showOpenDialog(JPanel()) # This is a hack to get a file path from the # sun.awt.shell.DefaultShellFolder object returned by the chooser fp = [str(i) for i in chooser.getSelectedFiles()] if len(fp) != 0: gd = GenericDialog("Name your output file") gd.addStringField("Score file name", "scores.csv") gd.showDialog() if not gd.wasCanceled(): scoreFile = gd.getNextString() scoreFile = os.path.join( os.path.split(fp[0])[0], scoreFile) cropDir = os.path.splitext( scoreFile)[0] + "_cropped" # Initialize the grid readers plateGrid = GridSet(fp,scoreFile,cropDir) plateGrid.openNext() # Show the GUI frame.setVisible(True) else: pass else: pass
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