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(): lowerThreshold = 80; upperThreshold = 255; stepNumber = 1 stepThreshold = 5; #p3DOCThreshold = 70; #p3DOCSlice = 1; p3DOCmin = 100; p3DOCmax = 2658480; gd = GenericDialog( "Parameters" ) gd.addMessage("Binary mask thresholds") gd.addNumericField("Lower Threshold", lowerThreshold, 0) # show 2 decimals gd.addNumericField("Upper threshold", upperThreshold, 0) # show 2 decimals gd.addNumericField("Step number", stepNumber, 0) # show 2 decimals gd.addNumericField("Step threshold", stepThreshold, 0) # show 2 decimals gd.addMessage("3D Object Counter parameters") #gd.addNumericField("threshold", p3DOCThreshold, 0) # show 2 decimals gd.addNumericField("min.", p3DOCmin, 0) # show 2 decimals gd.addNumericField("max.", p3DOCmax, 0) # show 2 decimals gd.showDialog() if gd.wasCanceled(): return # Read out the options lowerThreshold = gd.getNextNumber() upperThreshold = gd.getNextNumber() stepNumber = gd.getNextNumber() stepThreshold = gd.getNextNumber() #p3DOCThreshold = gd.getNextNumber() p3DOCmin = gd.getNextNumber() p3DOCmax = gd.getNextNumber() return lowerThreshold, upperThreshold, stepNumber, stepThreshold, p3DOCmin, p3DOCmax
def getSettings(img): """This function assesses (by returning a boolean value) if the filter can be applied to the image passed as argument. Will ask the user for new values if current parameters are undefined.""" global xradius, yradius, zradius canProceed = True if not img: IJ.error("No images open.") canProceed = False # Get new values if at least one of the parameters is 'null' if canProceed and None in (xradius, yradius, zradius): gd = GenericDialog("Median Filter") gd.addNumericField("X radius:", 2.0, 1) gd.addNumericField("Y radius:", 2.0, 1) gd.addNumericField("Z radius:", 2.0, 1) gd.showDialog() if gd.wasCanceled(): canProceed = False else: xradius = gd.getNextNumber() yradius = gd.getNextNumber() zradius = gd.getNextNumber() return canProceed
def getOptions(imp): gd = GenericDialog("Correct 3D Drift Options") channels = [] for ch in range(1, imp.getNChannels()+1 ): channels.append(str(ch)) methods = ["phase_correlation","center_of_mass"] gd.addChoice("Channel for registration:", channels, channels[0]) gd.addChoice("Method for registration:", methods, methods[1]) gd.addNumericField("Background value:", 0, 0) gd.addCheckbox("Multi_time_scale computation for enhanced detection of slow drifts?", False) gd.addCheckbox("Sub_pixel drift correction (possibly needed for slow drifts)?", False) gd.addCheckbox("Edge_enhance images for possibly improved drift detection?", False) gd.addCheckbox("Use virtualstack for saving the results to disk to save RAM?", False) gd.addCheckbox("Drift correct only data inside ROI?", False) gd.addCheckbox("Only compute drift vectors?", False) gd.addMessage("If you put a ROI, drift will only be computed in this region;\n the ROI will be moved along with the drift to follow your structure of interest.") gd.addSlider("z_min of ROI", 1, imp.getNSlices(), 1) gd.addSlider("z_max of ROI", 1, imp.getNSlices(), imp.getNSlices()) gd.showDialog() if gd.wasCanceled(): return channel = gd.getNextChoiceIndex() + 1 # zero-based method = gd.getNextChoiceIndex() + 1 # zero-based bg_value = gd.getNextNumber() multi_time_scale = gd.getNextBoolean() subpixel = gd.getNextBoolean() process = gd.getNextBoolean() virtual = gd.getNextBoolean() only_roi = gd.getNextBoolean() only_compute = gd.getNextBoolean() roi_z_min = int(gd.getNextNumber()) roi_z_max = int(gd.getNextNumber()) return channel, method, bg_value, virtual, multi_time_scale, subpixel, process, only_roi, only_compute, roi_z_min, roi_z_max
def getOptions(): gd = GenericDialog("Options") gd.addMessage("Filter Parameters") gd.addNumericField("Smoothing Parameter", 0.1, 2) # show 2 decimals gd.addNumericField("Patch radius", 2 , 1) gd.addNumericField("Search volume radius", 3 , 1) gd.showDialog() if gd.wasCanceled(): print "User canceled dialog!" sys.exit() # Read out the options beta = gd.getNextNumber() patchradius = gd.getNextNumber() searchradius = gd.getNextNumber() return beta, patchradius, searchradius
def getOptions(options, image): if 'channel' not in options: channels = [] for ch in range(1, image.getNChannels() + 1): channels.append("Channel " + "%i" % ch) dialog = GenericDialog("Select deconvolution parameters") dialog.addChoice("Channel to process", channels, None) dialog.addNumericField("Regularization parameter", 0.01, 2) dialog.addNumericField("Number of iterations", 50, 0) dialog.showDialog() if dialog.wasCanceled(): sys.exit(1) options['channel'] = dialog.getNextChoiceIndex() options['regparam'] = dialog.getNextNumber() options['iterations'] = dialog.getNextNumber() return options
def getRefIdDialog(): gd = GenericDialog("Reference Image") gd.addMessage("Preparing Turboreg(Rigidbody)\nSpecify image for reference") gd.addNumericField("Channel (C):", 2, 0) gd.addNumericField("Slice (Z):", 1, 0) gd.addNumericField("Frame (T):", 1, 0) gd.addMessage("Note: All fields start with 1 (not 0)") gd.showDialog() # if gd.wasCanceled(): print "User canceled dialog!" return # Read out the options c = int(gd.getNextNumber()) z = int(gd.getNextNumber()) t = int(gd.getNextNumber()) refId = [c,z,t] return refId
def get_options(): """Ask user for input values.""" dlg = GenericDialog("Options for Boxed Heatmap") dlg.addMessage("Boxed Heatmap settings") dlg.addMessage("Specify box size:") dlg.addNumericField("Width", 32, 0) dlg.addNumericField("Height", 32, 0) dlg.showDialog() if dlg.wasCanceled(): print "User canceled dialog." return None # Read out the options boxw = int(dlg.getNextNumber()) boxh = int(dlg.getNextNumber()) return boxw, boxh
def optionsDialog(): gd = GenericDialog('bPrairie2tif options') # label, value, digits gd.addNumericField('Median Filter Pixel Size (0 for no filtering)', globalOptions['medianFilter'], 0) gd.addCheckbox('Convert to 8 bit', globalOptions['convertToEightBit']) gd.showDialog() if gd.wasCanceled(): return None globalOptions['medianFilter'] = gd.getNextNumber() globalOptions['convertToEightBit'] = gd.getNextBoolean() return 1
def 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 getOptions(): global numberOfChannels global replaceExisting gd = GenericDialog("Options") gd.addNumericField("Number of channel", 2, 0) # show 0 decimals gd.addCheckbox("Replace Destination .tif files", 0) gd.addHelp("http://robertcudmore.org/software_index.html") gd.showDialog() if gd.wasCanceled(): print "User cancelled dialog." return -1 #read out options numberOfChannels = gd.getNextNumber() replaceExisting = gd.getNextBoolean() return 1 #int(numberOfChannels)
def getOptions(imp): gd = GenericDialog("Correct 3D Drift Options") channels = [] for ch in range(1, imp.getNChannels()+1 ): channels.append(str(ch)) gd.addChoice("Channel for registration:", channels, channels[0]) gd.addCheckbox("Multi_time_scale computation for enhanced detection of slow drifts?", False) gd.addCheckbox("Sub_pixel drift correction (possibly needed for slow drifts)?", False) gd.addCheckbox("Edge_enhance images for possibly improved drift detection?", False) gd.addCheckbox("Use virtualstack for saving the results to disk to save RAM?", False) gd.addMessage("If you put a ROI, drift will only be computed in this region;\n the ROI will be moved along with the drift to follow your structure of interest.") gd.showDialog() if gd.wasCanceled(): return channel = gd.getNextChoiceIndex() + 1 # zero-based multi_time_scale = gd.getNextBoolean() subpixel = gd.getNextBoolean() process = gd.getNextBoolean() virtual = gd.getNextBoolean() dt = gd.getNextNumber() return channel, virtual, multi_time_scale, subpixel, process
# def get_parameters(p, keys, num_data_sets): gd = GenericDialog("Please enter parameters") gd.addMessage("Found "+str(num_data_sets)+" data sets") gd.addStringField("analyse", "all"); gd.addMessage("Image analysis parameters:") gd.addMessage("Please note: the threshold values are inclusive!\nThus, to exlude pixels with value 255 the upper threshold needs to be 254") for k in keys: gd.addNumericField(k, p[k], 2); gd.showDialog() if gd.wasCanceled(): return to_be_analyzed = gd.getNextString() for k in keys: p[k] = gd.getNextNumber()
from ij.gui import GenericDialog from ij import IJ theImage = IJ.getImage() gd = GenericDialog("Set grid size") gd.addNumericField("Number of rows:",10,0) gd.addNumericField("Number of columns:",10,0) gd.showDialog() if (gd.wasOKed()): IJ.run("Colors...","foreground=cyan background=cyan selection=yellow") numRows = gd.getNextNumber() numCols = gd.getNextNumber() colDim = theImage.getWidth() / (numCols) rowDim = theImage.getHeight() / (numRows) rowStarts = range(rowDim,theImage.getHeight()-numRows,rowDim) colStarts = range(colDim,theImage.getWidth()-numCols,colDim) rowCenters = list(rowStarts) rowCenters.insert(0,0) colCenters = list(colStarts) colCenters.insert(0,0) for i in range(0,len(rowCenters)): rowCenters[i] = rowCenters[i] + rowDim - rowDim/8 for i in range(0,len(colCenters)): colCenters[i] = colCenters[i] + colDim/2 for i in rowStarts: IJ.makeLine(0,i,theImage.getWidth(),i) IJ.run("Draw","stack") for i in colStarts: IJ.makeLine(i,0,i,theImage.getHeight())
def getPixel(): # Get pixel size from user with dialog box. could return python dict or make custom class? Note user can return a NaN if doesnt enter numeric gd = GenericDialog("Pixel") gd.addNumericField("Pixel size desired (mm)", 6.4, 1) # default is 1 decimal gd.showDialog() Pixel_size = gd.getNextNumber() #6.4 # ENTER mm, remember tolerance is +/-30% return Pixel_size
def run(title): gd = GenericDialog("Record Window") gd.addMessage("Maximum number of frames to record.\nZero means infinite, interrupt with ESC key.") gd.addNumericField("Max. frames:", 50, 0) gd.addNumericField("Milisecond interval:", 300, 0) gd.addSlider("Start in (seconds):", 0, 20, 5) frames = [] titles = [] for f in Frame.getFrames(): if f.isEnabled() and f.isVisible(): frames.append(f) titles.append(f.getTitle()) gd.addChoice("Window:", titles, titles[0]) gd.addCheckbox("To file", False) gd.showDialog() if gd.wasCanceled(): return n_frames = int(gd.getNextNumber()) interval = gd.getNextNumber() / 1000.0 # in seconds frame = frames[gd.getNextChoiceIndex()] delay = int(gd.getNextNumber()) tofile = gd.getNextBoolean() dir = None if tofile: dc = DirectoryChooser("Directory to store image frames") dir = dc.getDirectory() if dir is None: return # dialog canceled snaps = [] borders = None executors = Executors.newFixedThreadPool(1) try: while delay > 0: IJ.showStatus("Starting in " + str(delay) + "s.") time.sleep(1) # one second delay -= 1 IJ.showStatus("Capturing frame borders...") bounds = frame.getBounds() robot = Robot() frame.toFront() time.sleep(0.5) # half a second borders = robot.createScreenCapture(bounds) IJ.showStatus("Recording " + frame.getTitle()) # Set box to the inside borders of the frame insets = frame.getInsets() box = bounds.clone() box.x = insets.left box.y = insets.top box.width -= insets.left + insets.right box.height -= insets.top + insets.bottom start = System.currentTimeMillis() / 1000.0 # in seconds last = start intervals = [] real_interval = 0 i = 1 fus = None if tofile: fus = [] # 0 n_frames means continuous acquisition while 0 == n_frames or (len(snaps) < n_frames and last - start < n_frames * interval): now = System.currentTimeMillis() / 1000.0 # in seconds real_interval = now - last if real_interval >= interval: last = now img = snapshot(frame, box) if tofile: fus.append(executors.submit(Saver(i, dir, bounds, borders, img, insets))) # will flush img i += 1 else: snaps.append(img) intervals.append(real_interval) else: time.sleep(interval / 5) # interrupt capturing: if IJ.escapePressed(): IJ.showStatus("Recording user-interrupted") break # debug: # print "insets:", insets # print "bounds:", bounds # print "box:", box # print "snap dimensions:", snaps[0].getWidth(), snaps[0].getHeight() # Create stack stack = None if tofile: for fu in snaps: fu.get() # wait on all stack = VirtualStack(bounds.width, bounds.height, None, dir) files = File(dir).list(TifFilter()) Arrays.sort(files) for f in files: stack.addSlice(f) else: stack = ImageStack(bounds.width, bounds.height, None) t = 0 for snap, real_interval in zip(snaps, intervals): bi = BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_RGB) g = bi.createGraphics() g.drawImage(borders, 0, 0, None) g.drawImage(snap, insets.left, insets.top, None) stack.addSlice(str(IJ.d2s(t, 3)), ImagePlus("", bi).getProcessor()) t += real_interval snap.flush() bi.flush() borders.flush() ImagePlus(frame.getTitle() + " recording", stack).show() IJ.showStatus("Done recording " + frame.getTitle()) except Exception, e: print "Some error ocurred:" print e.printStackTrace() IJ.showStatus("") if borders is not None: borders.flush() for snap in snaps: snap.flush()
return(theObjects[min_ind]) ## Main body of script ## Gets the channel to work on 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)+"-tile_1.csv"),range(1,stackInfo[0]+1))) gd = GenericDialog("Specify parameters...") gd.addChoice("Which_channel",channelTexts,channelTexts[0]) gd.addNumericField("Linear_pixel_num",512,0) gd.showDialog() if gd.wasOKed(): channel = int(gd.getNextChoice()) pixelLimit = int(gd.getNextNumber()) ## Obtains global coordinate system for tiles scale_info = estimate_scale_multiplier(parentLSMFilePath+"_tiles/tile_1.ome.tif",parentLSMFilePath+"_tiles/resized/tile_1.tif") coords = read_tileconfig_file(parentLSMFilePath+"_tiles/resized/TileConfiguration.registered.txt") upscaled_coords = normalize_coords_in_dict(upscale_coords(coords,scale_info[0])) #print upscaled_coords ## Parses each of the object files and converts coordinates to global coordinates objectDB = [[] for i in range(stackInfo[1])] filteredObjectDB = [[] for i in range(stackInfo[1])] duplicatedObjectDB = [[] for i in range(stackInfo[1])] uniqueDuplicatedObjectDB = [[] for i in range(stackInfo[1])] edgeOnlyObjectDB = [[] for i in range(stackInfo[1])] edgeContainedObjectDB = [[] for i in range(stackInfo[1])] containedMultipleObjectDB = [[] for i in range(stackInfo[1])]
def main(): # start with the sequence parameters fieldNames = ["Number of views", "Number of projections for each view", "Number of images for each projection (normally 1)", "Number of flats in each set", "Number of darks in each set", "Number of projections between each set of flats/darks"] fieldValues = [] # we start with zeros for the values # get user variables with imageJ dialog dialog = GenericDialog("Enter Scan Information") for i in range(6): dialog.addNumericField(fieldNames[i], 0, 0) dialog.addCheckbox("Two sets flats/darks between views?", False) dialog.showDialog() if dialog.wasCanceled(): return # exit function for i in range(6): fieldValues.append(int(dialog.getNextNumber())) extra = dialog.getNextBoolean() # make sure that none of the fields was left blank errmsg = "" for i in range(len(fieldNames)): if fieldValues[i] == "": errmsg += ('"%s" is a required field.\n\n' % fieldNames[i]) try: int(fieldValues[i]) except ValueError: errmsg += ('"%s" has to be an integer value.\n\n' % fieldNames[i]) if fieldValues[1] and fieldValues[5]: if int(fieldValues[1]) % int(fieldValues[5]) != 0: errmsg += ('Flat/Dark interval must divide evenly into projections\n\n') if errmsg != "": err_msg = GenericDialog("Error in Input") err_msg.addMessage(errmsg) err_msg.showDialog() return # exit if fieldValues is None: return # exit function fieldValues = [int(i) for i in fieldValues] # get the first item of the sequence using an imageJ dialog openFile = OpenDialog( "Select the first file of the sequence to rename.", None) fileName = openFile.getFileName() if fileName is None: return # exit function fileDir = openFile.getDirectory() first = fileDir + fileName path1, filename = os.path.split(first) basename = short(filename) # get directory for new files using imageJ dialog openOutDir = DirectoryChooser("Select directory for new files.") path2 = openOutDir.getDirectory() if path2 is None: return # exit function new_seq, fd_seq = gen_seq(fieldValues[0], fieldValues[1], fieldValues[2], fieldValues[3], fieldValues[4], fieldValues[5], extra) result = rename(basename, new_seq, fd_seq, path1, path2, fieldValues[0]) print result
# 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')
dialog.addStringField( "Root directory for storing results", root ) dialog.addCheckbox( "Render matrix to image at each iteration.", False ) dialog.addNumericField( "Start.", 0, 0 ) dialog.addNumericField( "Stop.", height, 0 ) dialog.addNumericField( "Interval size.", 1000, 0 ) dialog.addNumericField( "Overlap.", imgSource.getWidth()/2, 0 ) dialog.addNumericField( "Range.", c, 0 ) dialog.showDialog() if dialog.wasCanceled(): raise Exception( "dialog was canceled" ) root = dialog.getNextString() doRender = dialog.getNextBoolean() start = dialog.getNextNumber() stop = dialog.getNextNumber() interval = dialog.getNextNumber() overlap = dialog.getNextNumber() c = dialog.getNextNumber() step = interval - overlap ImageConverter( imgSource ).convertToGray32() stat = FloatStatistics( imgSource.getProcessor() ) normalizeBy = stat.max imgSource.getProcessor().multiply( 1.0 / normalizeBy ) nThreads = 1 serializeCorrelations = True
val_high = rt.getValueAsDouble(1,0) val_bleed = rt.getValueAsDouble(1,1) val_low = rt.getValueAsDouble(1,2) val_zero = rt.getValueAsDouble(1,3) val_target = val_high - val_low # scale_target = val_target / val_bleed scale_target = val_target / (val_bleed - val_zero) print scale_target gd = GenericDialog("Scale factor") gd.addNumericField("Scale factor on subtraction:",scale_target,3) gd.showDialog() if (gd.wasCanceled()): quit() scale = gd.getNextNumber() tempImage = image2.duplicate() for i in range(tempImage.getNSlices()): tempImage.setSliceWithoutUpdate(i+1) ip = tempImage.getProcessor() ip.subtract(val_zero) ip.multiply(scale) ic = ImageCalculator() newImage = ic.run("Subtract create stack",image1,tempImage) newImage.show() else: IJ.error("No images are open.")
# 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 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
print "\nwill not analyze file:",filename continue else: #print root print "\nanalyzing file:",filename imp = Opener().openImage(root, filename) analyse(imp, root, filename, thresholds) if __name__ == '__main__': srcDir = DirectoryChooser("Choose directory").getDirectory() #od = OpenDialog("Click on one of the image files in the folder to be analysed", None ) #filename = od.getFileName() #foldername = od.getDirectory() #foldername = "Z:/Tischi/projects/CellZome/2015-04-27--3D_Tissue/data" gd = GenericDialog("3D Tissue analysis"); gd.addNumericField("Threshold Ch1: ", 30, 0); gd.addNumericField("Threshold Ch2: ", 30, 0); gd.addNumericField("Threshold Ch3: ", 30, 0); gd.showDialog(); #if (gd.wasCanceled()): # return thresholds = [] thresholds.append(gd.getNextNumber()) thresholds.append(gd.getNextNumber()) thresholds.append(gd.getNextNumber()) #foldername = "Z:/Tischi/projects/CellZome/2015-04-29--3D_Tissue/subset" if None != srcDir: print "\n\n\n\nfoldername = "+srcDir getFilesAndAnalyze(srcDir, thresholds)
def open_Octopus_file(): # set up a file info structure fi = FileInfo() fi.fileFormat = fi.RAW fi.fileType=FileInfo.GRAY16_UNSIGNED fi.intelByteOrder = True fi.nImages = 1 op = OpenDialog("Choose Octopus .dth file...", "") if not op.getDirectory(): return False # get the file extension file_extension = re.search('(\.[a-z][a-z][a-z])', op.getFileName()).group(1) if file_extension != ".dth": dlg = GenericDialog("Warning") dlg.addMessage("Please select an octopus .dth file") dlg.showDialog() return False # now strip the filename into a stem and index file_parse = re.match('([a-zA-z0-9_]*_)([0-9]+)\.dth', op.getFileName()) file_stem = file_parse.group(1) file_index = int( file_parse.group(2) ) # ok now we need to parse the header info header = get_Octopus_header(op.getDirectory(), file_stem, file_index) fi.nImages = len(header['N']) # check to see whether we have a bit depth, if not, assume 16-bit if 'Bit_Depth' in header: print header['Bit_Depth'] bit_depth = int(header['Bit_Depth'][0]) if bit_depth == 8: fi.fileType = FileInfo.GRAY8 else: bit_depth = 16 # will assume that all files have the same size fi.width = int( header['W'][0] ) fi.height = int( header['H'][0] ) file_timestamp = strftime("%a, %d %b %Y %H:%M:%S", gmtime(float(header['Time'][0])) ) # make a new imagestack to store the data stack = ImageStack(fi.width, fi.height) # finally, we need to make a list of files to import as sometimes we have # non contiguous file numbers try: files = os.listdir(op.getDirectory()) except IOError: raise IOError( "No files exist in directory: " + op.getDirectory()) filenums = [] for f in files: # strip off the stem, and get the number targetfile = re.match(file_stem+'([0-9]+)\.dth', f) # only take thosefiles which match the formatting requirements if targetfile: filenums.append( int(targetfile.group(1)) ) # sort the file numbers sorted_filenums = sorted(filenums) # make a file stats string file_stats_str = file_stem + '\n' + str(fi.width) +'x' + str(fi.height) + 'x' + \ str(len(sorted_filenums)) +' ('+str(bit_depth)+'-bit)\n' + file_timestamp # now open a dialog to let the user set options dlg = GenericDialog("Load Octopus Stream (v"+__version__+")") dlg.addMessage(file_stats_str) dlg.addStringField("Title: ", file_stem) dlg.addNumericField("Start: ", 1, 0); dlg.addNumericField("End: ", len(sorted_filenums), 0) dlg.addCheckbox("Open headers", True) dlg.addCheckbox("Contiguous stream?", False) dlg.addCheckbox("8-bit unsigned", bit_depth==8) dlg.showDialog() # if we cancel the dialog, exit here if dlg.wasCanceled(): return # set some params file_title = dlg.getNextString() file_start = dlg.getNextNumber() file_end = dlg.getNextNumber() DISPLAY_HEADER = bool( dlg.getNextBoolean() ) # check the ranges if file_start > file_end: file_start, file_end = file_end, file_start if file_start < 1: file_start = 1 if file_end > len(sorted_filenums): file_end = len(sorted_filenums) # now set these to the actual file numbers in the stream file_start = sorted_filenums[int(file_start)-1] file_end = sorted_filenums[int(file_end)-1] files_to_open = [n for n in sorted_filenums if n>=file_start and n<=file_end] # if we've got too many, truncate the list if (len(files_to_open) * fi.nImages * fi.width * fi.height) > (MAX_FRAMES_TO_IMPORT*512*512): dlg = GenericDialog("Warning") dlg.addMessage("This may use a lot of memory. Continue?") dlg.showDialog() if dlg.wasCanceled(): return False IJ.log( "Opening file: " + op.getDirectory() + op.getFileName() ) IJ.log( file_stats_str + "\nFile range: " + str(files_to_open[0]) + \ "-" + str(files_to_open[-1]) +"\n" ) # make a results table for the metadata # NOTE: horrible looping at the moment, but works if DISPLAY_HEADER: rt = ResultsTable() # ok now we can put the files together into the stack for i in files_to_open: # open the original .dat file and get the stack fi.fileName = get_Octopus_filename( op.getDirectory(), file_stem, i) if os.path.isfile( fi.fileName ): fo = FileOpener(fi) imp = fo.open(False).getStack() # put the slices into the stack for im_slice in xrange( imp.getSize() ): ip = imp.getProcessor( im_slice+1 ) if bit_depth == 8: bi = ip.getBufferedImage() else: bi = ip.get16BitBufferedImage() stack.addSlice( file_title, ip ) if DISPLAY_HEADER: header = get_Octopus_header(op.getDirectory(), file_stem, i) for n in xrange(len(header['N'])): rt.incrementCounter() for k in header.keys(): rt.addValue(k, parse_header( header[k][n] ) ) else: break # done! output = ImagePlus('Octopus ('+file_stem+')', stack) output.show() if DISPLAY_HEADER: rt.show("Octopus header metadata") return True
import os import glob dirChooser = DirectoryChooser("Choose directory of images to normalize...") dirPath = dirChooser.getDirectory() scaleXs = [] if dirPath is not None: if not os.path.exists(dirPath + "resized"): os.mkdir(dirPath + "resized") gd = GenericDialog("Settings...") gd.addNumericField("Final scale factor:",0.5,2) gd.addCheckbox("Convert multichannel to RGB:",True) gd.showDialog() if (gd.wasOKed()): common_scale = gd.getNextNumber() convert_to_rgb = gd.getNextBoolean() filecollection = glob.glob(os.path.join(dirPath, '*.tif')) if (len(filecollection) > 0): for path in filecollection: theImage = IJ.openImage(path) calibration = theImage.getCalibration() scaleXs.append(calibration.pixelWidth) theImage.close() lc_scale = max(scaleXs) print lc_scale for path in filecollection: theImage = IJ.openImage(path) bname1 = os.path.basename(path) bname2 = os.path.splitext(bname1)[0] this_cal = theImage.getCalibration()
gd = GenericDialog("Set Parameters...") gd.addNumericField("Sizing_ratio (Final disk space / Initial disk space):",0.25,2) gd.addMessage("Directory size: " + str(dirSizeMB) + "MB") gd.addMessage("Maximum memory: " + str(memFijiMB) + "MB") mem_recs = calculate_memory_recs(dirSize,memFiji) print mem_recs for i in range(0,len(mem_recs)): ratio_rec = float(mem_recs[i]) / dirSizeMB if (ratio_rec > 1): ratio_rec = 1 print ratio_rec ratio_rec_str = "%.3f" % ratio_rec gd.addMessage(str(i+1)+"-channel: " + str(mem_recs[i]) + "MB; Ratio: " + ratio_rec_str) gd.showDialog() ratioRaw = gd.getNextNumber() ratio = math.sqrt(ratioRaw) if (gd.wasOKed()): filecollection = glob.glob(os.path.join(sourceDir, '*.ome.tif')) numFiles = len(filecollection) count = 1 for f in filecollection: bname1 = os.path.basename(f) bname2 = os.path.splitext(bname1)[0] bname3 = os.path.splitext(bname2)[0] print bname3 params = "open=[" + f + "] color_mode=Default view=Hyperstack stack_order=XYCZT" IJ.run("Bio-Formats Importer",params)
if Verbose: IJ.log('... ' + str(xpos) + ', ' + str(ypos) + ', ' + str(zpos)) outimp.getStack().getProcessor(int(zpos)+1).putPixel(int(xpos), int(ypos), i+1) return outimp Verbose = False if IJ.isMacro(): opt = getArgument()# ImageJ specific function Macro.getOptions() if len(opt) == 0: opt = OPT_PLACEHOLDER IJ.log(opt) optA = opt.split() Number_of_Cluster = int(optA[0]) Iteration = int(optA[1]) else: gd = GenericDialog("KMean Points Clustering", IJ.getInstance()) gd.addNumericField("Expected Number of Clusters", 4, 0) gd.addNumericField("Iterations", 10, 0) gd.showDialog() Number_of_Cluster = int(gd.getNextNumber()) Iteration = int(gd.getNextNumber()) imp = IJ.getImage() outimp = core(imp) outimp.show() IJ.run(outimp, "glasbey inverted", "")
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
IJ.run("Bio-Formats Importer", params); tileImage = WindowManager.getImage("tile_"+str(tiles[0])+".ome.tif") tileImage.setSlice(int(tileImage.getNSlices()/2)) else: ind = 1 tileDiskSize = os.path.getsize(imgDir+"tile_"+str(tiles[0])+".ome.tif") totalDiskSize = tileDiskSize * len(tiles) totalDiskSizeMB = totalDiskSize / 1048576 sizeGD = GenericDialog("Warning") sizeGD.addMessage("Memory used by selected tiles is " + str(totalDiskSizeMB) + "MB. Continue?") sizeGD.addCheckbox("Compute overlap",False) sizeGD.addNumericField("Tile overlap percentage",10,0) sizeGD.addCheckbox("Write fused image sequence to disk",False) sizeGD.showDialog() doComputeOverlap = sizeGD.getNextBoolean() overlapPctStr = str(sizeGD.getNextNumber()) doWriteToDisk = sizeGD.getNextBoolean() if (doComputeOverlap): overlapText = "compute_overlap ignore_z_stage" else: overlapText = "" if (doWriteToDisk): outputPath = imgDir + "substitched" diskWriteText = "image_output=[Write to disk] output_directory=[" + outputPath + "]" else: diskWriteText = "image_output=[Fuse and display]" if (sizeGD.wasOKed()): for t in tiles: shutil.copyfile(imgDir+"tile_"+str(t)+".ome.tif",imgDir+"temp/tile_"+str(ind)+".ome.tif") ind = ind + 1 IJ.showStatus("Beginning stitch...")
# Take a snapshot after a delay specified in a dialog # # The plugin has to fork, which is done by: # 1 - declaring a function to do the work, 'snasphot' # 2 - invoking the function via thread.start_new_thread, # which runs it in a separate thread. from ij import IJ from ij.gui import GenericDialog import thread import time def snapshot(delay): time.sleep(delay) IJ.doCommand('Capture Screen') gd = GenericDialog('Delay') gd.addSlider('Delay (secs.): ', 0, 20, 5) gd.showDialog() if not gd.wasCanceled(): # the 'extra' comma signals tuple, a kind of list in python. thread.start_new_thread(snapshot, (int(gd.getNextNumber()),))
from ij import IJ from ij.gui import GenericDialog from ij import ImageStack from ij import ImagePlus theImage = IJ.getImage() gd = GenericDialog("Expand stack...") gd.addNumericField("Multiple (natural number):",4,0) gd.showDialog() if (gd.wasOKed()): newStack = ImageStack(theImage.getWidth(),theImage.getHeight()) multiple = int(gd.getNextNumber()) for i in range(1,theImage.getNSlices()): theImage.setSlice(i) ip = theImage.getProcessor() for j in range(multiple): newip = ip.duplicate() newStack.addSlice(newip) resultImage = ImagePlus("stack_exp",newStack) resultImage.show()
theDirectory = theOpenDialog.getDirectory() theFileName = theOpenDialog.getFileName() baseName = os.path.splitext(theFileName)[0] # Creates the output directory if not os.path.exists(theDirectory + baseName + "_resized"): os.mkdir(theDirectory + baseName + "_resized") # Asks for parameters gd = GenericDialog("Set Parameters...") gd.addNumericField("Start tile:",1,0) gd.addNumericField("Finish tile:",9,0) gd.addNumericField("Final disk space / Initial disk space:",0.25,2) gd.addNumericField("Step size (higher is faster but uses more memory):",10,0) gd.showDialog() startTile = int(gd.getNextNumber()) finishTile = int(gd.getNextNumber()) ratioRaw = gd.getNextNumber() ratio = math.sqrt(ratioRaw) stepSize = int(gd.getNextNumber()) # Performs scaling if (gd.wasOKed()): anchorTiles = range(startTile,finishTile+1,stepSize) print anchorTiles for i in anchorTiles: if (i+stepSize-1 > finishTile): lastAnchorTile = finishTile else: lastAnchorTile = i+stepSize-1
from ij.plugin import ImageCalculator from ij import WindowManager theImage = IJ.getImage() gd = GenericDialog("Options...") channelText = [("Channel " + str(ch+1)) for ch in range(theImage.getNChannels())] gd.addChoice("Amplified_channel",channelText,channelText[0]) gd.addChoice("Reference_channel",channelText,channelText[-1]) gd.addNumericField("Amplifying_ratio",1,0) gd.addCheckbox("Remove_bleedthrough",True) gd.addCheckbox("Correct_for_refraction",True) gd.showDialog() if gd.wasOKed(): amplifyChannel = gd.getNextChoiceIndex() + 1 refChannel = gd.getNextChoiceIndex() + 1 ampFactor = gd.getNextNumber() doRemoveBleedthrough = gd.getNextBoolean() doCorrectRefraction = gd.getNextBoolean() chImages = ChannelSplitter.split(theImage) ## After this step, the image to operate on is "nextStepImage" if doRemoveBleedthrough: params = ("bleeding_channel=" + str(refChannel) + " bloodied_channel=" + str(amplifyChannel) + " " + "allowable_saturation_percent=1.0 rsquare_threshold=0.50") IJ.run("Remove Bleedthrough (automatic)", params) unbledImage = WindowManager.getImage("Corrected_ch" + str(amplifyChannel)) mergingImages = [unbledImage,chImages[refChannel-1].duplicate()] nextStepImage = RGBStackMerge.mergeChannels(mergingImages,True) #nextStepImage.show() unbledImage.close() for img in mergingImages: