def cell_processor(imp_particles, imp_measure, folder, impname, channel_name): # Get ROI manager instance, save to zip rm = RoiManager.getInstance() if not rm: rm = RoiManager() rm.reset() imp_particles.show() # Wait for user to add ROIs to manager Prefs.multiPointMode = True pause = WaitForUserDialog( "Select ROIs of interest and add to manager \n \nPress OK to continue") pause.show() # get the ROI manager and save rm = RoiManager.getInstance() rm.runCommand("save selected", os.path.join(folder, impname + "_cells_ROIs.zip")) # select image to measure and show imp_measure.show() pixel_collector(rm, imp_measure, channel_name, impname, folder) return rm
def threshold_and_binarise(imp): """Return thresholded stack""" print("performing segmentation on channel: " + imp.getTitle()); stats = StackStatistics(imp); IJ.run(imp, "Subtract...", "value={} stack".format(stats.min)); IJ.run(imp, "Divide...", "value={} stack".format((stats.max - stats.min)/255.0)); WaitForUserDialog("pre 8-bit").show(); imp = robust_convertStackToGray8(imp); WaitForUserDialog("post 8-bit").show(); # Apply automatic THRESHOLD to differentiate cells from background histo = StackStatistics(imp).histogram; thresh_lev = AutoThresholder().getThreshold(AutoThresholder.Method.Default, histo); print(thresh_lev); min_volume = int(float(imp.getHeight() * imp.getWidth() * imp.getNSlices())/100); IJ.run(imp, "3D Simple Segmentation", "low_threshold=" + str(thresh_lev + 1) + " min_size=" + str(min_volume) + " max_size=-1"); fit_basis_imp = WM.getImage("Seg"); bin_imp = WM.getImage("Bin"); bin_imp.changes=False; bin_imp.close(); IJ.setThreshold(fit_basis_imp, 1, 65535); IJ.run(fit_basis_imp, "Convert to Mask", "method=Default background=Dark list"); #IJ.run(fit_basis_imp, "Fill Holes", "stack"); # IJ.run("3D Fill Holes", ""); return fit_basis_imp;
def filter_original(): # Filter out noise, keep edges IJ.run("Median...", "radius=4") # Enhance contrast IJ.run("Enhance Local Contrast (CLAHE)", "blocksize=19 histogram=256 maximum=3 mask=*None*"); # Find edges IJ.run("Find Edges"); # Threshold...conservatively! IJ.run('Threshold...', 'Default Dark') dial = WaitForUserDialog('Please threshold conservatively.') dial.show() # Now run the hough circles IJ.run("Hough Circles", "minimum=8 maximum=9 increment=1 number=0 threshold=0") image.changes = False image.close() # Select the hough space image dial = WaitForUserDialog('Select the hough space image.') dial.show() # Filter out all but the small points #IJ.run("Bandpass Filter...", "filter_large=7 filter_small=4 suppress=None tolerance=5 autoscale saturate") # Threshold the centers of the points IJ.run('Threshold...', 'Default Dark') dial = WaitForUserDialog('Please threshold circle centers. Should be near max.') dial.show() # Select all the particles, deal with ROI's IJ.run("Analyze Particles...", "size=0-Infinity include add");
def z_crop(imp): """trim a z stack based on interactively-defined start and end points""" WaitForUserDialog("Choose first z plane and click OK...").show() start_z = imp.getZ() WaitForUserDialog("Now choose last z plane and click OK...").show() end_z = imp.getZ() frames = imp.getNFrames() channels = imp.getNChannels() #current_channel = imp.getC(); dupimp = Duplicator().run(imp, 1, channels, start_z, end_z, 1, frames) imp.changes = False imp.close() dupimp.show() #autoset_zoom(dupimp); return dupimp, (start_z, end_z)
def assisted_SNTtrace(context, imp): ''' Calls SNT in a given img for user assisted tracing. Uses WaitForUserDialog to confirm the end of tracing operations. Returns list of SNT Paths. ''' snt = prepare_SNT(context, imp) pafm = snt.getPathAndFillManager() dialog = WaitForUserDialog("Go to next step...", "Press ok when tracing is done.") dialog.show() if dialog.escPressed(): raise RuntimeError("Canceled by the user.") SNTpaths = pafm.getPaths() return SNTpaths
def perform_cropping(imp, info, output_folder, default_path): imp.show() imp.setC(info.get_mosaic_labeled_ch()) IJ.run("Enhance Contrast", "saturated=0.35") zcrop_imp, z_lims = z_crop(imp) info.set_z_crop_frames(z_lims) info.set_mosaic_labeled_ch(imp.getC()) IJ.setTool("rect") zcrop_imp.hide() imp2 = ZProjector.run(zcrop_imp, "max") imp2.show() imp2.setC(info.get_mosaic_labeled_ch()) crop_roi = None while crop_roi is None: WaitForUserDialog("Select XY region to crop...").show() crop_roi = imp2.getRoi() if crop_roi.getType(): info.set_xy_crop_rect( str([(x, y) for x, y in zip(crop_roi.getPolygon().xpoints, crop_roi.getPolygon().ypoints)])) else: info.set_xy_crop_rect(crop_roi.getBounds().toString()) imp2.close() zcrop_imp.show() zcrop_imp.setRoi(crop_roi) IJ.run("Crop", "") if crop_roi.getType(): IJ.run(zcrop_imp, "Make Inverse", "") inv_roi = zcrop_imp.getRoi() IJ.run(zcrop_imp, "Set...", "value=0 stack") IJ.run(zcrop_imp, "Make Inverse", "") # zcrop_imp = z_crop_finetune(zcrop_imp, info); return imp, zcrop_imp, info, info.get_input_file_path()
def z_crop(imp): """trim a z stack based on interactively-defined start and end points""" IJ.setTool("zoom") IJ.run("Brightness/Contrast...") imp.setZ(1) WaitForUserDialog("Choose first z plane and click OK...").show() start_z = imp.getZ() WaitForUserDialog("Now choose last z plane and click OK...").show() end_z = imp.getZ() frames = imp.getNFrames() channels = imp.getNChannels() imp.killRoi() dupimp = Duplicator().run(imp, 1, channels, start_z, end_z, 1, frames) imp.hide() dupimp.show() return dupimp, (start_z, end_z)
def twist_and_unwrap(imp): """from the output of angular projection, define an axis along which to unzip the vessel and return this unzipped image""" tile_imp = make_tiled_imp(imp) tile_imp.show() IJ.setTool("freeline") WaitForUserDialog( "Input required...", "Please draw the line down which unwrapping should occur...").show() roi = tile_imp.getRoi() if roi is None: raise ValueError unwrap_poly = roi.getPolygon() unwrap_poly_xs = [x for x in unwrap_poly.xpoints] unwrap_poly_ys = [y for y in unwrap_poly.ypoints] # extend to the top and bottom of the image: unwrap_poly_xs.insert(0, unwrap_poly_xs[0]) unwrap_poly_xs.append(unwrap_poly_xs[-1]) if unwrap_poly_ys[0] < unwrap_poly_ys[-1]: unwrap_poly_ys.insert(0, 1) unwrap_poly_ys.append(imp.getHeight()) else: unwrap_poly_ys.insert(0, imp.getHeight()) unwrap_poly_ys.append(1) unwrap_axis = [(x, y) for (x, y) in zip(unwrap_poly_xs, unwrap_poly_ys)] unwrapped_projection_imp = do_unwrap(tile_imp, unwrap_axis, imp_title=imp.getTitle()) return unwrapped_projection_imp, unwrap_axis
def auto_threshold(imp, ch_name, is_auto_thresh, method="IsoData"): if is_auto_thresh: IJ.setAutoThreshold(imp, "{} dark".format(method)) thres_min = imp.getProcessor().getMinThreshold() else: imp.show() IJ.run("Threshold...") # this is the method to wait the user set up the threshold wu = WaitForUserDialog("Set manual threshold for {}".format(ch_name), "Use slider to adjust threshold and press OK") wu.show() thres_min = imp.getProcessor().getMinThreshold() thres_max = imp.getProcessor().getMaxThreshold() IJ.log(" -- {}: Min threshold {}".format(ch_name, thres_min)) IJ.setThreshold(imp, thres_min, thres_max) imp.hide() WindowManager.getWindow("Threshold").close() return thres_min
def Generate_segmented_manual(imp, channel, threshold_method, filtersize): imp_Threshold_1 = ExtractChannel(imp1, channel) imp_Threshold_1.setTitle(("Threshold" + "Channel" + str(channel))) imp_Threshold_1.show() IJ.run(imp_Threshold_1, "Median...", "radius=" + str(filtersize)) IJ.run(imp_Threshold_1, "Subtract Background...", "rolling=50") IJ.run("Threshold...") # this is the method to wait the user set up the threshold WaitForUserDialog("Threshold", "set a threshold").show() thres_min = imp_Threshold_1.getProcessor().getMinThreshold() thres_max = imp_Threshold_1.getProcessor().getMaxThreshold() IJ.setThreshold(imp_Threshold_1, thres_min, thres_max) #Prefs.blackBackground = True; IJ.run(imp_Threshold_1, "Convert to Mask", "") return imp_Threshold_1
def z_crop_finetune(imp, info): """define z cropping to allow freehand definition of lower bounds""" imp.setC(info.get_mosaic_labeled_ch()) rot_imp = rot3d(imp, axis='x') imp.close() rot_imp.show() IJ.setTool("freehand") WaitForUserDialog("Select XZ region to crop...").show() crop_roi = rot_imp.getRoi() if crop_roi is None: return if crop_roi.getType(): info.set_zx_crop_rect( str([(x, y) for x, y in zip(crop_roi.getPolygon().xpoints, crop_roi.getPolygon().ypoints)])) else: info.set_zx_crop_rect(crop_roi.getBounds().toString()) if crop_roi.getType(): IJ.run(zcrop_imp, "Make Inverse", "") inv_roi = zcrop_imp.getRoi() IJ.run(zcrop_imp, "Set...", "value=0 stack") IJ.run(zcrop_imp, "Make Inverse", "") imp = rot3d(rot_imp, axis='x') return imp
def combine_two_channel_segments(imp1, imp2, binary_imp1, binary_imp2): """Use both channels to segment the vessel...""" # two choices - # EITHER: combine median-filtered channels BEFORE segmentation: this means that correlation between # planes is maintained thanks to 3d segmentation # OR: make choice about which channel to use (or whether to combine - how?) AFTER segmentation - potentially easier, so start with this stack = ImageStack(imp1.getWidth(), imp1.getHeight()) for zidx in range(1, imp1.getNSlices() + 1): WaitForUserDialog("about to combine channels for slice " + str(zidx)).show() print("zidx = " + str(zidx)) ch1_snr = calculate_snr(imp1, binary_imp1, zidx) print("Ch1 snr = " + str(ch1_snr)) ch2_snr = calculate_snr(imp2, binary_imp2, zidx) print("Ch2 snr = " + str(ch2_snr)) if (0.75 * ch1_snr) > ch2_snr: binary_imp1.setZ(zidx) ip = binary_imp1.getProcessor() else: print("USING MCH CHANNEL!") binary_imp2.setZ(zidx) ip = binary_imp2.getProcessor() stack.addSlice(ip) return ImagePlus("Combined thresholded channels", stack)
def mean(numbers): return float(sum(numbers)) / max(len(numbers), 1) timepoints = imp1.getNFrames() ort = ResultsTable() ort.setPrecision(3) IJ.run(imp1, "Select All", "") stats_all = imp1.getStatistics( Measurements.AREA) print str(stats_all.area) IJ.run(imp1, "Select None", "") WaitForUserDialog("Select cell-free region","select background free of cells").show() stats_background = imp1.getStatistics( Measurements.AREA) print str(stats_background.area) IJ.run(imp1, "Select None", "") for i in range (1, timepoints+1): IJ.run(imp1, "Select None", "") imp1.setT(i) # Extact channel to Threshold, set automatic threshold imp_threshold= ExtractTimpepointChannel(imp1, 1, i) if do_dog_C1: imp_DoG = DoG(imp_threshold,1,3) else:
from jarray import zeros from java.awt import Color from ij.gui import PointRoi, OvalRoi, Overlay from ij.plugin.frame import RoiManager from ij.gui import WaitForUserDialog, Toolbar #remove all the previous ROIS imp = IJ.getImage() rm = RoiManager.getInstance() if not rm: rm = RoiManager() rm.runCommand("reset") #ask the user to define a selection and get the bounds of the selection IJ.setTool(Toolbar.RECTANGLE) WaitForUserDialog("Select the area,then click OK.").show() boundRect = imp.getRoi() imp.setRoi(boundRect) rm.addRoi(boundRect) imp = IJ.getImage() cal = imp.getCalibration() # in microns img = IJF.wrap(imp) print(img.dimensions) # Create a variable of the correct type (UnsignedByteType) for the value-extended view zero = img.randomAccess().get().createVariable() # Run the difference of Gaussian cell = 30.0 # microns in diameter
def process(self,imp): # extract nucleus channel, 8-bit and twice binned imp.setC(self.nucleusChannel) ip = imp.getChannelProcessor().duplicate() ip = ip.convertToByteProcessor() ip = ip.bin(4) nucleus = ImagePlus("nucleus_channel", ip) # threshold image and separate clumped nuclei IJ.run(nucleus, "Auto Threshold", "method=Otsu white setthreshold show"); IJ.run(nucleus, "Make Binary", "thresholded remaining black"); IJ.run(nucleus, "Watershed", ""); directory = imp.getTitle() directory = directory.replace(" ", "_")\ .replace(",", "_")\ .replace("#", "_series")\ .replace("...", "")\ .replace(".","_") directory = os.path.join(self.exportDir, directory) sliceDirectory = os.path.join(directory, "slices") print directory print sliceDirectory if not os.path.exists(sliceDirectory): os.makedirs(sliceDirectory) # Create a table to store the results table = ResultsTable() # Create a hidden ROI manager, to store a ROI for each blob or cell #roim = RoiManager(True) # remove small particles and border particles pa = ParticleAnalyzer(\ ParticleAnalyzer.ADD_TO_MANAGER | ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES,\ Measurements.CENTER_OF_MASS,\ table,\ self.minArea, self.maxArea,\ 0.0,1.0) if pa.analyze(nucleus): print "All ok, number of particles: ", table.size() else: print "There was a problem in analyzing", imp, nucleus table.save(os.path.join(directory, "rt.csv")) # read the center of mass coordinates cmx = table.getColumn(0) cmy = table.getColumn(1) if self.debug: imp.show() i=0 for i in range(0, min(self.nCells,table.size())): # ROI around the cell cmx = table.getValue("XM",i) cmy = table.getValue("YM",i) x = 4 * cmx - (self.boxSize - 1) / 2 y = 4 * cmy - (self.boxSize - 1) / 2 if (x < self.edge or y < self.edge or x > imp.getWidth() - self.edge or y > imp.getHeight() - self.edge): continue roi = Roi(x,y,self.boxSize,self.boxSize) imp.setRoi(roi, False) cellStack = ImageStack(self.boxSize, self.boxSize) for z in range(1, imp.getNSlices() + 1): imp.setSlice(z) for c in range(1, imp.getNChannels() + 1): imp.setC(c) # copy ROI to stack imp.copy() impSlice = imp.getClipboard() cellStack.addSlice(impSlice.getProcessor()) if self.slices: sliceTitle = "cell_%s_z%s_c%s" % (str(i).zfill(4), str(z).zfill(3), str(c)) print sliceTitle IJ.saveAsTiff(impSlice, os.path.join(sliceDirectory, sliceTitle)) impSlice.close() title = "cell_" + str(i).zfill(4) cell = ImagePlus(title, cellStack) # save ROI image IJ.saveAsTiff(cell, os.path.join(directory, title)) cell.close() if self.debug: imp.updateAndDraw() wait = Wait("particle done") wait.show()
def wait(message=None): if message == None: message = 'press ok to continue' wfug = WaitForUserDialog('Waiting for user', message) wfug.show()
def main(): #print (sys.version_info) # debug #print(sys.path) # debug data_root = r'C:\Users\dougk\Desktop\test' # debug output_root = r'C:\Users\dougk\Desktop\test' #debug #default_directory = r'C:\\Users\\Doug\\Desktop\\test'; #data_root, output_root = file_location_chooser(default_directory); if (data_root is None) or (output_root is None): raise IOError("File location dialogs cancelled!") timestamp = datetime.strftime(datetime.now(), "%Y-%m-%d %H.%M.%S") output_path = os.path.join(output_root, (timestamp + " output")) for file_path in filterByFileType(os.listdir(data_root), '.tif'): subfolder_name = os.path.splitext(file_path)[0] output_subfolder = os.path.join(output_path, subfolder_name) print(output_subfolder) os.makedirs(output_subfolder) imps = bf.openImagePlus(os.path.join(data_root, file_path)) imp = imps[0] imp.show() h = imp.height w = imp.width slices = imp.getNSlices() channels = imp.getNChannels() frames = imp.getNFrames() # rotation step - since using multiples of 90, TransformJ.Turn is more efficient IJ.run("Enhance Contrast", "saturated=0.35") angleZ = 1 while ((angleZ % 90) > 0): gd = GenericDialog("Rotate?") gd.addMessage( "Define rotation angle - increments of 90. Apical at top") gd.addNumericField("Rotation angle", 0, 0) gd.showDialog() angleZ = int(gd.getNextNumber()) if (angleZ > 1): IJ.run("TransformJ Turn", "z-angle=" + str(angleZ) + " y-angle=0 x-angle=0") imp.close() imp = WindowManager.getCurrentImage() imp.setTitle(file_path) # trim time series IJ.run("Enhance Contrast", "saturated=0.35") imp.setDisplayMode(IJ.COLOR) WaitForUserDialog( "Scroll to the first frame of the period of interest and click OK" ).show() start_frame = imp.getT() WaitForUserDialog( "Scroll to the last frame of the period of interest and click OK" ).show() end_frame = imp.getT() trim_imp = Duplicator().run(imp, 1, channels, 1, slices, start_frame, end_frame) imp.close() trim_imp.show() dup_imp = Duplicator().run(trim_imp) # create images to process and find bounds for dup_imps = ChannelSplitter().split(dup_imp) myo_imp = dup_imps[1] mem_imp = dup_imps[0] FileSaver(myo_imp).saveAsTiffStack( os.path.join(output_subfolder, "myosin_channel.tif")) FileSaver(mem_imp).saveAsTiffStack( os.path.join(output_subfolder, "membrane_channel.tif")) # set basal bounds myo_imp.show() ImageConverter(myo_imp).convertToGray8() frames = myo_imp.getNFrames() gb = GaussianBlur() for fridx in range(0, frames): myo_imp.setSliceWithoutUpdate(fridx + 1) ip = myo_imp.getProcessor() gb.blurGaussian(ip, 5.0, 1.0, 0.02) # assymmetrical Gaussian IJ.run(myo_imp, "Convert to Mask", "method=Otsu background=Dark calculate") IJ.run("Despeckle", "stack") title = myo_imp.getTitle() # assume that first frame is good quality image... basal_edges = find_basal_edges(myo_imp) #myo_imp.hide() mem_imp.hide() # draw some edges for checking roim = RoiManager() xs = [x for x in range(1, trim_imp.getWidth() + 1)] trim_imp.show() for fridx in range(0, myo_imp.getNFrames()): trim_imp.setPosition(2, 1, fridx + 1) IJ.run("Enhance Contrast", "saturated=0.35") roi = PolygonRoi(xs, basal_edges[fridx], Roi.POLYLINE) trim_imp.setRoi(roi) roim.addRoi(roi)
gd = NonBlockingGenericDialog("Set slice params...") gd.addNumericField("Slice start:",1,0) gd.addNumericField("Slice end:",theImage.getNSlices(),0) gd.showDialog() if (gd.wasOKed()): startSlice = gd.getNextNumber() endSlice = gd.getNextNumber() width = theImage.getWidth() height = theImage.getHeight() newStack = ImageStack(width,height) t_line = 240 for i in range(startSlice,endSlice+1): theImage.setSlice(i) waiter = WaitForUserDialog("Set ROI","Set ROI for thresholding region") waiter.show() roi = theImage.getRoi() newip = theImage.getProcessor().duplicate() newip.setColor(0) newip.fillOutside(roi) newip.snapshot() newip.setThreshold(0,t_line,ImageProcessor.BLACK_AND_WHITE_LUT) newImage = ImagePlus("toggler",newip) newImage.show() doSameSlice = True while (doSameSlice): accept_waiter = NonBlockingGenericDialog("Thresholding...") accept_waiter.addNumericField("Threshold:",t_line,0)
summary[color[i] + "-ROI-count"] = "NA" #gets the mean grey intensity of the channel summary[color[i] + "-intensity"] = channel.getStatistics(Measurements.MEAN).mean channel.show() #Sets the thresholds from the dialog box IJ.setThreshold(channel, thresholds[color[i]], 255) if thresholdMode: channel.show() IJ.run("Threshold...") WaitForUserDialog("Title", "Adjust threshold for " + color[i]).show() #Get the threshold you've used summary[color[i] + "-threshold-used"] = ImageProcessor.getMinThreshold(channel.getProcessor()) #Threshold and watershed IJ.run(channel, "Convert to Mask", "") IJ.run(channel, "Watershed", "") table = ResultsTable() roim = RoiManager(True) ParticleAnalyzer.setRoiManager(roim)
from ij import IJ from ij.gui import WaitForUserDialog # Draw a line dial = WaitForUserDialog('Draw a line that will be rotated to horizontal.') dial.show() cur_image = IJ.getImage() cur_roi = cur_image.getRoi() cur_angle = cur_roi.getAngle() print cur_angle # Angles must be between 90 and -90 degrees...currently are not but it's fine as my # system has inversion symmetry along the y-axis IJ.run(cur_image, "Rotate... ", "angle=" +str(cur_angle) + " grid=0 interpolation=Bicubic stack")
def process(subDir, subsubDir, outputDirectory, filename): subFolder = subDir + "/" + subsubDir # Opens the d0 image and sets default properties imp = IJ.openImage(inputDirectory + subFolder + '/' + filename) IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) # Sets the threshold and watersheds. for more details on image processing, see https://imagej.nih.gov/ij/developer/api/ij/process/ImageProcessor.html ic = ImageConverter(imp) ic.convertToGray8() imp.updateAndDraw() dup = imp.duplicate() IJ.run( dup, "Convolve...", "text1=[-1 -1 -1 -1 -1\n-1 -1 -1 -1 -1\n-1 -1 24 -1 -1\n-1 -1 -1 -1 -1\n-1 -1 -1 -1 -1\n] normalize" ) stats = dup.getStatistics(Measurements.MEAN | Measurements.MIN_MAX | Measurements.STD_DEV) dup.close() blurry = (stats.mean < 18 and stats.stdDev < 22) or stats.max < 250 IJ.setThreshold(imp, lowerBounds[0], 255) IJ.run(imp, "Convert to Mask", "") IJ.run(imp, "Watershed", "") if displayImages: imp.show() WaitForUserDialog("Title", "Look at image").show() # Counts and measures the area of particles and adds them to a table called areas. Also adds them to the ROI manager table = ResultsTable() roim = RoiManager(True) ParticleAnalyzer.setRoiManager(roim) pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA, table, 15, 9999999999999999, 0.2, 1.0) pa.setHideOutputImage(True) pa.analyze(imp) if not displayImages: imp.changes = False imp.close() areas = table.getColumn(0) # This loop goes through the remaining channels for the other markers, by replacing the d0 at the end with its corresponding channel # It will save all the area fractions into a 2d array called areaFractionsArray areaFractionsArray = [] areaMeansArray = [] means = [] totalAreas = [] for chan in channels: v, x = chan # Opens each image and thresholds imp = IJ.openImage(inputDirectory + subFolder + '/' + filename.replace("d0.TIF", "d" + str(x) + ".TIF")) IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) ic = ImageConverter(imp) ic.convertToGray8() imp.updateAndDraw() stats = imp.getStatistics(Measurements.MEAN) means.append(stats.mean) areaMeans = [] for roi in roim.getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.MEAN) areaMeans.append(stats.mean) IJ.setThreshold(imp, lowerBounds[x], 255) IJ.run(imp, "Convert to Mask", "") if displayImages: imp.show() WaitForUserDialog("Title", "Look at image").show() stats = imp.getStatistics(Measurements.AREA_FRACTION) totalAreas.append(stats.areaFraction) # Measures the area fraction of the new image for each ROI from the ROI manager. areaFractions = [] for roi in roim.getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.AREA_FRACTION) areaFractions.append(stats.areaFraction) # Saves the results in areaFractionArray areaFractionsArray.append(areaFractions) areaMeansArray.append(sum(areaMeans) / len(areaMeans)) if not displayImages: imp.changes = False imp.close() roim.close() # Figures out what well the image is a part of ind = filename.index("p00_0_") row = filename[ind + 6:ind + 7] column = str(int(filename[ind + 7:ind + 9])) # Creates the summary dictionary which will correspond to a single row in the output csv, with each key being a column summary = {} # Finds the name of the well from the nameArray 2d array if row in nameArray: if column in nameArray[row]: summary['Name'] = nameArray[row][column] summary['Image'] = filename summary['Directory'] = subDir summary['SubDirectory'] = subsubDir summary['Row'] = row summary['Column'] = column # Adds usual columns summary['size-average'] = 0 summary['#nuclei'] = 0 summary['all-negative'] = 0 summary['too-big-(>' + str(tooBigThreshold) + ')'] = 0 summary['too-small-(<' + str(tooSmallThreshold) + ')'] = 0 summary['image-quality'] = blurry # Creates the fieldnames variable needed to create the csv file at the end. fieldnames = [ 'Name', 'Directory', 'SubDirectory', 'Image', 'Row', 'Column', 'size-average', 'image-quality', 'too-big-(>' + str(tooBigThreshold) + ')', 'too-small-(<' + str(tooSmallThreshold) + ')', '#nuclei', 'all-negative' ] # Adds the columns for each individual marker (ignoring Dapi since it was used to count nuclei) for chan in channels: v, x = chan summary[v + "-positive"] = 0 summary[v + "-intensity"] = means[x] summary[v + "-area"] = totalAreas[x] summary[v + "-intensity-in-nuclei"] = areaMeansArray[x] summary[v + "-area-fraction-in-nuclei"] = sum( areaFractionsArray[x]) / len(areaFractionsArray[x]) fieldnames.append(v + "-positive") fieldnames.append(v + "-intensity") fieldnames.append(v + "-area") fieldnames.append(v + "-intensity-in-nuclei") fieldnames.append(v + "-area-fraction-in-nuclei") # Adds the column for colocalization between first and second marker if len(channels) > 2: summary[channels[1][0] + '-' + channels[2][0] + '-positive'] = 0 fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-positive') # Adds the columns for colocalization between all three markers if len(channels) > 3: summary[channels[1][0] + '-' + channels[3][0] + '-positive'] = 0 summary[channels[2][0] + '-' + channels[3][0] + '-positive'] = 0 summary[channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive'] = 0 fieldnames.append(channels[1][0] + '-' + channels[3][0] + '-positive') fieldnames.append(channels[2][0] + '-' + channels[3][0] + '-positive') fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive') # Loops through each particle and adds it to each field that it is True for. areaCounter = 0 if not (areas is None): for z, area in enumerate(areas): if not (area is None or summary is None): if area > tooBigThreshold: summary['too-big-(>' + str(tooBigThreshold) + ')'] += 1 elif area < tooSmallThreshold: summary['too-small-(<' + str(tooSmallThreshold) + ')'] += 1 else: summary['#nuclei'] += 1 areaCounter += area temp = 0 for y, chan in enumerate(channels): v, x = chan if areaFractionsArray[y][z] > areaFractionThreshold: summary[chan[0] + '-positive'] += 1 if x != 0: temp += 1 if temp == 0: summary['all-negative'] += 1 if len(channels) > 2: if areaFractionsArray[1][z] > areaFractionThreshold: if areaFractionsArray[2][z] > areaFractionThreshold: summary[channels[1][0] + '-' + channels[2][0] + '-positive'] += 1 if len(channels) > 3: if areaFractionsArray[1][z] > areaFractionThreshold: if areaFractionsArray[3][z] > areaFractionThreshold: summary[channels[1][0] + '-' + channels[3][0] + '-positive'] += 1 if areaFractionsArray[2][z] > areaFractionThreshold: if areaFractionsArray[3][z] > areaFractionThreshold: summary[channels[2][0] + '-' + channels[3][0] + '-positive'] += 1 if areaFractionsArray[1][ z] > areaFractionThreshold: summary[channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive'] += 1 # Calculate the average of the particles sizes if float(summary['#nuclei']) > 0: summary['size-average'] = round(areaCounter / summary['#nuclei'], 2) # Opens and appends one line on the final csv file for the subfolder (remember that this is still inside the loop that goes through each image) with open(outputDirectory + "/" + outputName + ".csv", 'a') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames, extrasaction='ignore', lineterminator='\n') if os.path.getsize(outputDirectory + "/" + outputName + ".csv") < 1: writer.writeheader() writer.writerow(summary)
def do_tubefitting(im_path=im_test_path, metadata_path=metadata_test_path, output_path=output_path, save_output=False): # todo: fix things so that all operations use a consistent definition of background rather than changing Prefs on the fly... Prefs.blackBackground = False info = PrescreenInfo() info.load_info_from_json(metadata_path) z_xy_ratio = abs( info.get_z_plane_spacing_um()) / info.get_xy_pixel_size_um() #z_xy_ratio = 1.0; bfimp = bf.openImagePlus(im_path) imp = bfimp[0] imp.show() IJ.run(imp, "Set Scale...", "distance=0 known=0 pixel=1 unit=pixel") imp = utils.downsample_for_isotropy(imp, extra_downsample_factor=1.0, info=info) rot_seg_imp, rot_proj_imp, egfp_mch_imps = split_and_rotate(imp, info) depth = rot_seg_imp.getNSlices() if rot_seg_imp.getNSlices( ) > rot_seg_imp.getNFrames() else rot_seg_imp.getNFrames() width = rot_seg_imp.getWidth() height = int(round(rot_seg_imp.getHeight() * z_xy_ratio)) # Apply 3d MEDIAN FILTER to denoise and emphasise vessel-associated voxels fit_basis_imp = threshold_and_binarise(rot_seg_imp, z_xy_ratio) fit_basis_imp.setTitle("fit_basis_imp") fit_basis_imp.show() # plane-wise, use binary-outline # say the non-zero points then make up basis for fitting to be performed per http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html rois = [] centres = [] major_axes = [] roi_imp = IJ.createImage("rois", width, height, depth, 32) pts_stack = ImageStack(width, height + 1) IJ.run(imp, "Line Width...", "line=3") for zidx in range(fit_basis_imp.getNSlices()): fit_basis_imp.setZ(zidx + 1) IJ.run(fit_basis_imp, "Outline", "slice") IJ.run(fit_basis_imp, "Create Selection", "") roi = fit_basis_imp.getRoi() fit_basis_imp.killRoi() pts = [(pt.x, pt.y) for pt in roi.getContainedPoints()] clean_pts = convex_hull_pts(pts) clean_pts = [(x, z_xy_ratio * y) for (x, y) in clean_pts] # make a stack of clean points... ip = FloatProcessor(width, height + 1) pix = ip.getPixels() for pt in clean_pts: pix[int(pt[1]) * width + int(pt[0])] = 128 pts_stack.addSlice(ip) centre, angle, axl = ellipse_fitting.fit_ellipse(clean_pts) major_axes.append(max(axl)) centres.append(centre) rot_seg_imp.setZ(zidx + 1) ellipse_roi = ellipse_fitting.generate_ellipse_roi(centre, angle, axl) rois.append(ellipse_roi) IJ.run(imp, "Line Width...", "line=1") cal = imp.getCalibration() smooth_centres, tangent_vecs = generate_smoothed_vessel_axis( centres, pixel_size_um=cal.pixelDepth) for zidx in range(fit_basis_imp.getNSlices()): centre = smooth_centres[zidx] major_axis = major_axes[zidx] ellipse_roi = EllipseRoi(centre[0] - 2, centre[1], centre[0] + 2, centre[1], 1.0) roi_imp.setZ(zidx + 1) roi_imp.setRoi(ellipse_roi) IJ.run(roi_imp, "Set...", "value=" + str(roi_imp.getProcessor().maxValue()) + " slice") pts_stack_imp = ImagePlus("Cleaned points", pts_stack) pts_stack_imp.setTitle("pts_stack_imp") pts_stack_imp.show() rot_seg_imp.changes = False rot_seg_imp.close() egfp_imp = egfp_mch_imps[0] mch_imp = egfp_mch_imps[1] imps_to_combine = [egfp_mch_imps[1], egfp_mch_imps[0], roi_imp] egfp_imp.show() mch_imp.show() roi_imp.show() print("box height um = " + str(roi_imp.getNSlices() * info.get_xy_pixel_size_um())) IJ.run( egfp_imp, "Size...", "width=" + str(width) + " height=" + str(height) + " depth=" + str(depth) + " average interpolation=Bilinear") IJ.run( mch_imp, "Size...", "width=" + str(width) + " height=" + str(height) + " depth=" + str(depth) + " average interpolation=Bilinear") #IJ.run("Merge Channels...", "c1=[" + mch_imp.getTitle() + # "] c2=[" + egfp_imp.getTitle() + # "] c7=[" + roi_imp.getTitle() + "] create keep"); composite_imp = RGBStackMerge().mergeChannels(imps_to_combine, False) print(composite_imp) composite_imp.show() print("end of vessel centerline id step, image dims = ({}x{}x{})".format( composite_imp.getWidth(), composite_imp.getHeight(), composite_imp.getNSlices())) WaitForUserDialog("pause").show() # do qc here? #WM.getImage("Composite").addImageListener(UpdateRoiImageListener(rois)); IJ.run(roi_imp, "8-bit", "") if save_output: FileSaver(composite_imp).saveAsTiffStack( os.path.join(output_path, "segmentation result.tif")) print(roi_imp) FileSaver(roi_imp).saveAsTiff( os.path.join(output_path, "vessel axis.tif")) egfp_imp.changes = False mch_imp.changes = False roi_imp.changes = False fit_basis_imp.changes = False pts_stack_imp.changes = False egfp_imp.close() mch_imp.close() #roi_imp.close(); fit_basis_imp.close() pts_stack_imp.close() zcoords = [i for i in range(composite_imp.getNSlices())] xyz_smooth_centres = [(x, y, z) for ((x, y), z) in zip(smooth_centres, zcoords)] composite_imp2 = straighten_vessel(composite_imp, xyz_smooth_centres, save_output=True) composite_imp3 = straighten_vessel(composite_imp2, xyz_smooth_centres, it=2, save_output=True) return composite_imp3
else: IJ.showStatus("Need to pick an ROI first before running this option") self.workRoiCheckbox.setState(False) ## Main body of script starts here od = OpenDialog("Select parent LSM file...") parentLSMFilePath = od.getPath() if parentLSMFilePath is not None: tileConfigFilePath = parentLSMFilePath + "_tiles/resized/TileConfiguration.registered.txt" scale_info = estimate_scale_multiplier(parentLSMFilePath+"_tiles/tile_1.ome.tif",parentLSMFilePath+"_tiles/resized/tile_1.tif") print scale_info coords = read_tileconfig_file(tileConfigFilePath) full_keys = ["tile_"+str(i) for i in range(1,len(coords.keys())+1)] coords_vals = normalize_coords_in_list(get_list_from_dict(full_keys,coords)) im = IJ.getImage() wfud = WaitForUserDialog("Select a freehand ROI, then click here") wfud.show() roi = im.getRoi() if (roi is not None): float_poly = roi.getFloatPolygon() containing_tiles_superlist = [] for i in range(float_poly.npoints): containing_tiles_superlist.append(find_containing_tiles([float_poly.xpoints[i],float_poly.ypoints[i],0],coords_vals,scale_info[1],scale_info[2])) upscaled_coords = upscale_coords(coords,scale_info[0]) containing_tiles_dict = rearrange_tile_list(containing_tiles_superlist) copy_fullsize_tiles(["tile_"+key for key in containing_tiles_dict.keys()],parentLSMFilePath+"_tiles/",parentLSMFilePath+"_tiles/subtiles/",".ome.tif") subupcoords_vals = normalize_coords_in_list(get_list_from_dict(["tile_"+key for key in containing_tiles_dict.keys()],upscaled_coords)) hadStitched = False if len(containing_tiles_dict.keys())>1: for i in containing_tiles_dict.keys(): IJ.log("Opened tile " + str(i))
def runTrackMate(imp): import fiji.plugin.trackmate.Settings as Settings import fiji.plugin.trackmate.Model as Model import fiji.plugin.trackmate.SelectionModel as SelectionModel import fiji.plugin.trackmate.TrackMate as TrackMate import fiji.plugin.trackmate.Logger as Logger import fiji.plugin.trackmate.detection.DetectorKeys as DetectorKeys import fiji.plugin.trackmate.detection.DogDetectorFactory as DogDetectorFactory import fiji.plugin.trackmate.tracking.sparselap.SparseLAPTrackerFactory as SparseLAPTrackerFactory import fiji.plugin.trackmate.tracking.LAPUtils as LAPUtils import fiji.plugin.trackmate.visualization.hyperstack.HyperStackDisplayer as HyperStackDisplayer import fiji.plugin.trackmate.features.FeatureFilter as FeatureFilter import fiji.plugin.trackmate.features.FeatureAnalyzer as FeatureAnalyzer import fiji.plugin.trackmate.features.spot.SpotContrastAndSNRAnalyzerFactory as SpotContrastAndSNRAnalyzerFactory import fiji.plugin.trackmate.action.ExportStatsToIJAction as ExportStatsToIJAction import fiji.plugin.trackmate.io.TmXmlReader as TmXmlReader import fiji.plugin.trackmate.action.ExportTracksToXML as ExportTracksToXML import fiji.plugin.trackmate.io.TmXmlWriter as TmXmlWriter import fiji.plugin.trackmate.features.ModelFeatureUpdater as ModelFeatureUpdater import fiji.plugin.trackmate.features.SpotFeatureCalculator as SpotFeatureCalculator import fiji.plugin.trackmate.features.spot.SpotContrastAndSNRAnalyzer as SpotContrastAndSNRAnalyzer import fiji.plugin.trackmate.features.spot.SpotIntensityAnalyzerFactory as SpotIntensityAnalyzerFactory import fiji.plugin.trackmate.features.track.TrackSpeedStatisticsAnalyzer as TrackSpeedStatisticsAnalyzer import fiji.plugin.trackmate.util.TMUtils as TMUtils import fiji.plugin.trackmate.visualization.trackscheme.TrackScheme as TrackScheme import fiji.plugin.trackmate.visualization.PerTrackFeatureColorGenerator as PerTrackFeatureColorGenerator #------------------------- # Instantiate model object #------------------------- nFrames = imp.getNFrames() model = Model() # Set logger #model.setLogger(Logger.IJ_LOGGER) #------------------------ # Prepare settings object #------------------------ settings = Settings() settings.setFrom(imp) # Configure detector settings.detectorFactory = DogDetectorFactory() settings.detectorSettings = { DetectorKeys.KEY_DO_SUBPIXEL_LOCALIZATION: True, DetectorKeys.KEY_RADIUS: 12.30, DetectorKeys.KEY_TARGET_CHANNEL: 1, DetectorKeys.KEY_THRESHOLD: 100., DetectorKeys.KEY_DO_MEDIAN_FILTERING: False, } # Configure tracker settings.trackerFactory = SparseLAPTrackerFactory() settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap() settings.trackerSettings['LINKING_MAX_DISTANCE'] = 10.0 settings.trackerSettings['GAP_CLOSING_MAX_DISTANCE'] = 10.0 settings.trackerSettings['MAX_FRAME_GAP'] = 3 # Add the analyzers for some spot features. # You need to configure TrackMate with analyzers that will generate # the data you need. # Here we just add two analyzers for spot, one that computes generic # pixel intensity statistics (mean, max, etc...) and one that computes # an estimate of each spot's SNR. # The trick here is that the second one requires the first one to be in # place. Be aware of this kind of gotchas, and read the docs. settings.addSpotAnalyzerFactory(SpotIntensityAnalyzerFactory()) settings.addSpotAnalyzerFactory(SpotContrastAndSNRAnalyzerFactory()) # Add an analyzer for some track features, such as the track mean speed. settings.addTrackAnalyzer(TrackSpeedStatisticsAnalyzer()) settings.initialSpotFilterValue = 1 print(str(settings)) #---------------------- # Instantiate trackmate #---------------------- trackmate = TrackMate(model, settings) #------------ # Execute all #------------ ok = trackmate.checkInput() if not ok: sys.exit(str(trackmate.getErrorMessage())) ok = trackmate.process() if not ok: sys.exit(str(trackmate.getErrorMessage())) #---------------- # Display results #---------------- selectionModel = SelectionModel(model) displayer = HyperStackDisplayer(model, selectionModel, imp) displayer.render() displayer.refresh() #--------------------- # Select correct spots #--------------------- # Prepare display. sm = SelectionModel(model) color = PerTrackFeatureColorGenerator(model, 'TRACK_INDEX') # launch TrackScheme to select spots and tracks trackscheme = TrackScheme(model, sm) trackscheme.setDisplaySettings('TrackColoring', color) trackscheme.render() # Update image with TrackScheme commands view = HyperStackDisplayer(model, sm, imp) view.setDisplaySettings('TrackColoring', color) view.render() # Wait for the user to select correct spots and tracks before collecting data dialog = WaitForUserDialog( "Spots", "Delete incorrect spots and edit tracks if necessary. (Press ESC to cancel analysis)" ) dialog.show() if dialog.escPressed(): IJ.run("Remove Overlay", "") imp.close() return ([], nFrames) # The feature model, that stores edge and track features. #model.getLogger().log('Found ' + str(model.getTrackModel().nTracks(True)) + ' tracks.') fm = model.getFeatureModel() crds_perSpot = [] for id in model.getTrackModel().trackIDs(True): # Fetch the track feature from the feature model.(remove """ to enable) """v = fm.getTrackFeature(id, 'TRACK_MEAN_SPEED') model.getLogger().log('') model.getLogger().log('Track ' + str(id) + ': mean velocity = ' + str(v) + ' ' + model.getSpaceUnits() + '/' + model.getTimeUnits())""" trackID = str(id) track = model.getTrackModel().trackSpots(id) spot_track = {} for spot in track: sid = spot.ID() # Fetch spot features directly from spot. x = spot.getFeature('POSITION_X') y = spot.getFeature('POSITION_Y') t = spot.getFeature('FRAME') q = spot.getFeature('QUALITY') snr = spot.getFeature('SNR') mean = spot.getFeature('MEAN_INTENSITY') #model.getLogger().log('\tspot ID = ' + str(sid) + ', x='+str(x)+', y='+str(y)+', t='+str(t)+', q='+str(q) + ', snr='+str(snr) + ', mean = ' + str(mean)) spot_track[t] = (x, y) crds_perSpot.append(spot_track) #print ("Spot", crds_perSpot.index(spot_track),"has the following coordinates:", crds_perSpot[crds_perSpot.index(spot_track)]) return (crds_perSpot, nFrames)
def process(subFolder, outputDirectory, filename): imp = IJ.openImage(inputDirectory + subFolder + '/' + filename) imp.show() IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) ic = ImageConverter(imp) dup = imp.duplicate() dup_title = dup.getTitle() ic.convertToGray8() imp.updateAndDraw() IJ.run("Threshold...") IJ.setThreshold(218, 245) IJ.run(imp, "Convert to Mask", "") rm = RoiManager() imp.getProcessor().setThreshold(0, 0, ImageProcessor.NO_LUT_UPDATE) boundroi = ThresholdToSelection.run(imp) rm.addRoi(boundroi) imp.changes = False imp.close() images = [None] * 5 intensities = [None] * 5 blobsarea = [None] * 5 blobsnuclei = [None] * 5 cells = [None] * 5 bigareas = [None] * 5 IJ.run(dup, "Colour Deconvolution", "vectors=[H DAB]") images[0] = getImage(dup_title + "-(Colour_1)") images[1] = getImage(dup_title + "-(Colour_2)") images[2] = getImage(dup_title + "-(Colour_3)") images[2].close() for chan in channels: v, x = chan imp = images[x] imp.show() for roi in rm.getRoiManager().getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.MEAN | Measurements.AREA) intensities[x] = stats.mean bigareas[x] = stats.area rm.runCommand(imp, "Show None") rm.close() # Opens the ch00 image and sets default properties imp = images[0].duplicate() IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) # Sets the threshold and watersheds. for more details on image processing, see https://imagej.nih.gov/ij/developer/api/ij/process/ImageProcessor.html imp.show() setTempCurrentImage(imp) ic = ImageConverter(imp) imp.updateAndDraw() IJ.run(imp, "Gaussian Blur...", "sigma=" + str(blur)) imp.updateAndDraw() imp.show() IJ.run("Threshold...") IJ.setThreshold(30, lowerBounds[0]) if displayImages: imp.show() WaitForUserDialog( "Title", "Adjust threshold for nuclei. Current region is: " + region).show() IJ.run(imp, "Convert to Mask", "") # Counts and measures the area of particles and adds them to a table called areas. Also adds them to the ROI manager table = ResultsTable() roim = RoiManager() pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA, table, 5, 9999999999999999, 0.05, 1.0) pa.setHideOutputImage(True) imp = IJ.getImage() # imp.getProcessor().invert() pa.analyze(imp) imp.changes = False imp.close() areas = table.getColumn(0) # This loop goes through the remaining channels for the other markers, by replacing the ch00 at the end with its corresponding channel # It will save all the area fractions into a 2d array called areaFractionsArray areaFractionsArray = [None] * 5 maxThresholds = [] for chan in channels: v, x = chan # Opens each image and thresholds imp = images[x] IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) imp.show() setTempCurrentImage(imp) ic = ImageConverter(imp) ic.convertToGray8() imp.updateAndDraw() rm.runCommand(imp, "Show None") rm.runCommand(imp, "Show All") rm.runCommand(imp, "Show None") imp.show() IJ.selectWindow(imp.getTitle()) IJ.run("Threshold...") IJ.setThreshold(20, lowerBounds[x]) if displayImages: WaitForUserDialog( "Title", "Adjust threshold for " + v + ". Current region is: " + region).show() ip = imp.getProcessor() maxThresholds.append(ip.getMaxThreshold()) IJ.run(imp, "Convert to Mask", "") # Measures the area fraction of the new image for each ROI from the ROI manager. areaFractions = [] for roi in roim.getRoiManager().getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.AREA_FRACTION) areaFractions.append(stats.areaFraction) # Saves the results in areaFractionArray areaFractionsArray[x] = areaFractions roim.close() for chan in channels: v, x = chan imp = images[x] imp.deleteRoi() imp.updateAndDraw() setTempCurrentImage(imp) roim = RoiManager() pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA, table, 15, 9999999999999999, 0.2, 1.0) pa.analyze(imp) blobs = [] cell = [] for roi in roim.getRoiManager().getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.AREA) blobs.append(stats.area) if stats.area > tooSmallThresholdDAB and stats.area < tooBigThresholdDAB: cell.append(stats.area) blobsarea[x] = sum(blobs) blobsnuclei[x] = len(blobs) cells[x] = len(cell) imp.changes = False imp.close() roim.reset() roim.close() # Creates the summary dictionary which will correspond to a single row in the output csv, with each key being a column summary = {} summary['Image'] = filename summary['Directory'] = subFolder # Adds usual columns summary['size-average'] = 0 summary['#nuclei'] = 0 summary['all-negative'] = 0 summary['too-big-(>' + str(tooBigThreshold) + ')'] = 0 summary['too-small-(<' + str(tooSmallThreshold) + ')'] = 0 # Creates the fieldnames variable needed to create the csv file at the end. fieldnames = [ 'Directory', 'Image', 'size-average', 'too-big-(>' + str(tooBigThreshold) + ')', 'too-small-(<' + str(tooSmallThreshold) + ')', '#nuclei', 'all-negative' ] for row in info: if row['Animal ID'] == filename.replace('s', '-').replace( 'p', '-').split('-')[0]: for key, value in row.items(): fieldnames.insert(0, key) summary[key] = value # Adds the columns for each individual marker (ignoring Dapi since it was used to count nuclei) summary["tissue-area"] = bigareas[0] fieldnames.append("tissue-area") for chan in channels: v, x = chan summary[v + "-HEMO-cells"] = 0 fieldnames.append(v + "-HEMO-cells") summary[v + "-intensity"] = intensities[x] fieldnames.append(v + "-intensity") summary[v + "-area"] = blobsarea[x] fieldnames.append(v + "-area") summary[v + "-area/tissue-area"] = blobsarea[x] / bigareas[0] fieldnames.append(v + "-area/tissue-area") summary[v + "-particles"] = blobsnuclei[x] fieldnames.append(v + "-particles") summary[v + "-cells"] = cells[x] fieldnames.append(v + "-cells") summary[v + "-particles/tissue-area"] = blobsnuclei[x] / bigareas[0] fieldnames.append(v + "-particles/tissue-area") fieldnames.append(v + "-HEMO-Cells/tissue-area") # Adds the column for colocalization between first and second marker if len(channels) > 2: summary[channels[1][0] + '-' + channels[2][0] + '-positive'] = 0 fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-positive') # Adds the columns for colocalization between all three markers if len(channels) > 3: summary[channels[1][0] + '-' + channels[3][0] + '-positive'] = 0 summary[channels[2][0] + '-' + channels[3][0] + '-positive'] = 0 summary[channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive'] = 0 fieldnames.append(channels[1][0] + '-' + channels[3][0] + '-positive') fieldnames.append(channels[2][0] + '-' + channels[3][0] + '-positive') fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive') # Loops through each particle and adds it to each field that it is True for. areaCounter = 0 for z, area in enumerate(areas): if area > tooBigThreshold: summary['too-big-(>' + str(tooBigThreshold) + ')'] += 1 elif area < tooSmallThreshold: summary['too-small-(<' + str(tooSmallThreshold) + ')'] += 1 else: summary['#nuclei'] += 1 areaCounter += area temp = 0 for chan in channels: v, x = chan if areaFractionsArray[x][z] > areaFractionThreshold[0]: summary[chan[0] + '-HEMO-cells'] += 1 if x != 0: temp += 1 if temp == 0: summary['all-negative'] += 1 if len(channels) > 2: if areaFractionsArray[1][z] > areaFractionThreshold[1]: if areaFractionsArray[2][z] > areaFractionThreshold[2]: summary[channels[1][0] + '-' + channels[2][0] + '-positive'] += 1 if len(channels) > 3: if areaFractionsArray[1][z] > areaFractionThreshold[1]: if areaFractionsArray[3][z] > areaFractionThreshold[3]: summary[channels[1][0] + '-' + channels[3][0] + '-positive'] += 1 if areaFractionsArray[2][z] > areaFractionThreshold[2]: if areaFractionsArray[3][z] > areaFractionThreshold[3]: summary[channels[2][0] + '-' + channels[3][0] + '-positive'] += 1 if areaFractionsArray[1][z] > areaFractionThreshold[1]: summary[channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive'] += 1 # Calculate the average of the particles sizes for chan in channels: v, x = chan summary[v + "-cells/tissue-area"] = summary[v + "-cells"] / bigareas[0] if float(summary['#nuclei']) > 0: summary['size-average'] = round(areaCounter / summary['#nuclei'], 2) if displayImages: fieldnames = ["Directory", "Image"] for chan in channels: v, x = chan summary[v + "-threshold"] = maxThresholds[x] fieldnames.append(v + "-threshold") allMaxThresholds[v + "-" + region].append(maxThresholds[x]) # Opens and appends one line on the final csv file for the subfolder (remember that this is still inside the loop that goes through each image) with open(outputName, 'a') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames, extrasaction='ignore', lineterminator='\n') if os.path.getsize(outputName) < 1: writer.writeheader() writer.writerow(summary)
coords = d['roi']['coordinates'][0] img_width = imp.getWidth() img_height = imp.getHeight() bound_width = d['bounds']['maxX'] - d['bounds']['minX'] bound_height = d['bounds']['maxY'] - d['bounds']['minY'] scale = img_width * 1.0 / bound_width print 'scale', scale xvals = [(x - d['bounds']['minX']) * scale for x, y in coords[:-1]] yvals = [(y - d['bounds']['minY']) * scale for x, y in coords[:-1]] print xvals, yvals fpoly = PolygonRoi(xvals, yvals, Roi.POLYGON) imp.setRoi(fpoly) dlg = WaitForUserDialog('testing') dlg.show() roi = imp.getRoi() fpoly = roi.getFloatPolygon() coords = [[]] for x, y in zip(fpoly.xpoints, fpoly.ypoints): x = (x / scale) + d['bounds']['minX'] y = (y / scale) + d['bounds']['minY'] coords[0].append([x, y]) for x, y in zip(fpoly.xpoints[:1], fpoly.ypoints[:1]): x = (x / scale) + d['bounds']['minX'] y = (y / scale) + d['bounds']['minY'] coords[0].append([x, y]) d['roi']['coordinates'] = coords imp.close()
def process(subFolder, outputDirectory, filename): imp = IJ.openImage(inputDirectory + subFolder + '/' + rreplace(filename, "_ch00.tif", ".tif")) IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) ic = ImageConverter(imp) ic.convertToGray8() IJ.setThreshold(imp, 2, 255) IJ.run(imp, "Convert to Mask", "") IJ.run(imp, "Remove Outliers...", "radius=5" + " threshold=50" + " which=Dark") IJ.run(imp, "Remove Outliers...", "radius=5" + " threshold=50" + " which=Bright") imp.getProcessor().invert() rm = RoiManager(True) imp.getProcessor().setThreshold(0, 0, ImageProcessor.NO_LUT_UPDATE) boundroi = ThresholdToSelection.run(imp) rm.addRoi(boundroi) if not displayImages: imp.changes = False imp.close() images = [None] * 5 intensities = [None] * 5 blobsarea = [None] * 5 blobsnuclei = [None] * 5 bigAreas = [None] * 5 for chan in channels: v, x = chan images[x] = IJ.openImage(inputDirectory + subFolder + '/' + rreplace(filename, "_ch00.tif", "_ch0" + str(x) + ".tif")) imp = images[x] for roi in rm.getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.MEAN | Measurements.AREA) intensities[x] = stats.mean bigAreas[x] = stats.area rm.close() # Opens the ch00 image and sets default properties imp = IJ.openImage(inputDirectory + subFolder + '/' + filename) IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) # Sets the threshold and watersheds. for more details on image processing, see https://imagej.nih.gov/ij/developer/api/ij/process/ImageProcessor.html ic = ImageConverter(imp) ic.convertToGray8() IJ.run(imp, "Remove Outliers...", "radius=2" + " threshold=50" + " which=Dark") IJ.run(imp, "Gaussian Blur...", "sigma=" + str(blur)) IJ.setThreshold(imp, lowerBounds[0], 255) if displayImages: imp.show() IJ.run(imp, "Convert to Mask", "") IJ.run(imp, "Watershed", "") if not displayImages: imp.changes = False imp.close() # Counts and measures the area of particles and adds them to a table called areas. Also adds them to the ROI manager table = ResultsTable() roim = RoiManager(True) ParticleAnalyzer.setRoiManager(roim) pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA, table, 15, 9999999999999999, 0.2, 1.0) pa.setHideOutputImage(True) #imp = impM # imp.getProcessor().invert() pa.analyze(imp) areas = table.getColumn(0) # This loop goes through the remaining channels for the other markers, by replacing the ch00 at the end with its corresponding channel # It will save all the area fractions into a 2d array called areaFractionsArray areaFractionsArray = [None] * 5 for chan in channels: v, x = chan # Opens each image and thresholds imp = images[x] IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) ic = ImageConverter(imp) ic.convertToGray8() IJ.setThreshold(imp, lowerBounds[x], 255) if displayImages: imp.show() WaitForUserDialog("Title", "Adjust Threshold for Marker " + v).show() IJ.run(imp, "Convert to Mask", "") # Measures the area fraction of the new image for each ROI from the ROI manager. areaFractions = [] for roi in roim.getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.AREA_FRACTION) areaFractions.append(stats.areaFraction) # Saves the results in areaFractionArray areaFractionsArray[x] = areaFractions roim.close() for chan in channels: v, x = chan imp = images[x] imp.deleteRoi() roim = RoiManager(True) ParticleAnalyzer.setRoiManager(roim) pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA, table, 15, 9999999999999999, 0.2, 1.0) pa.analyze(imp) blobs = [] for roi in roim.getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.AREA) blobs.append(stats.area) blobsarea[x] = sum(blobs) blobsnuclei[x] = len(blobs) if not displayImages: imp.changes = False imp.close() roim.reset() roim.close() # Creates the summary dictionary which will correspond to a single row in the output csv, with each key being a column summary = {} summary['Image'] = filename summary['Directory'] = subFolder # Adds usual columns summary['size-average'] = 0 summary['#nuclei'] = 0 summary['all-negative'] = 0 summary['too-big-(>' + str(tooBigThreshold) + ')'] = 0 summary['too-small-(<' + str(tooSmallThreshold) + ')'] = 0 # Creates the fieldnames variable needed to create the csv file at the end. fieldnames = [ 'Name', 'Directory', 'Image', 'size-average', 'too-big-(>' + str(tooBigThreshold) + ')', 'too-small-(<' + str(tooSmallThreshold) + ')', '#nuclei', 'all-negative' ] # Adds the columns for each individual marker (ignoring Dapi since it was used to count nuclei) summary["organoid-area"] = bigAreas[x] fieldnames.append("organoid-area") for chan in channels: v, x = chan summary[v + "-positive"] = 0 fieldnames.append(v + "-positive") summary[v + "-intensity"] = intensities[x] fieldnames.append(v + "-intensity") summary[v + "-blobsarea"] = blobsarea[x] fieldnames.append(v + "-blobsarea") summary[v + "-blobsnuclei"] = blobsnuclei[x] fieldnames.append(v + "-blobsnuclei") # Adds the column for colocalization between first and second marker if len(channels) > 2: summary[channels[1][0] + '-' + channels[2][0] + '-positive'] = 0 fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-positive') # Adds the columns for colocalization between all three markers if len(channels) > 3: summary[channels[1][0] + '-' + channels[3][0] + '-positive'] = 0 summary[channels[2][0] + '-' + channels[3][0] + '-positive'] = 0 summary[channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive'] = 0 fieldnames.append(channels[1][0] + '-' + channels[3][0] + '-positive') fieldnames.append(channels[2][0] + '-' + channels[3][0] + '-positive') fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive') # Loops through each particle and adds it to each field that it is True for. areaCounter = 0 for z, area in enumerate(areas): log.write(str(area)) log.write("\n") if area > tooBigThreshold: summary['too-big-(>' + str(tooBigThreshold) + ')'] += 1 elif area < tooSmallThreshold: summary['too-small-(<' + str(tooSmallThreshold) + ')'] += 1 else: summary['#nuclei'] += 1 areaCounter += area temp = 0 for chan in channels: v, x = chan if areaFractionsArray[x][z] > areaFractionThreshold[ 0]: #theres an error here im not sure why. i remember fixing it before summary[chan[0] + '-positive'] += 1 if x != 0: temp += 1 if temp == 0: summary['all-negative'] += 1 if len(channels) > 2: if areaFractionsArray[1][z] > areaFractionThreshold[1]: if areaFractionsArray[2][z] > areaFractionThreshold[2]: summary[channels[1][0] + '-' + channels[2][0] + '-positive'] += 1 if len(channels) > 3: if areaFractionsArray[1][z] > areaFractionThreshold[1]: if areaFractionsArray[3][z] > areaFractionThreshold[3]: summary[channels[1][0] + '-' + channels[3][0] + '-positive'] += 1 if areaFractionsArray[2][z] > areaFractionThreshold[2]: if areaFractionsArray[3][z] > areaFractionThreshold[3]: summary[channels[2][0] + '-' + channels[3][0] + '-positive'] += 1 if areaFractionsArray[1][z] > areaFractionThreshold[1]: summary[channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive'] += 1 # Calculate the average of the particles sizes if float(summary['#nuclei']) > 0: summary['size-average'] = round(areaCounter / summary['#nuclei'], 2) # Opens and appends one line on the final csv file for the subfolder (remember that this is still inside the loop that goes through each image) with open(outputDirectory + "/" + outputName + ".csv", 'a') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames, extrasaction='ignore', lineterminator='\n') if os.path.getsize(outputDirectory + "/" + outputName + ".csv") < 1: writer.writeheader() writer.writerow(summary)
from ij import WindowManager from ij.gui import WaitForUserDialog plotWindow = WindowManager.getActiveWindow() X = plotWindow.getXValues() Y = plotWindow.getYValues() zeroY = [int(idx) for idx, val in enumerate(Y) if (val == 0)] print(zeroY) labelWindow = WindowManager.getWindow("Label Edition") labelWindow.toFront() for idx, zeroFrame in enumerate(zeroY): labelWindow.showSlice(zeroFrame) WaitForUserDialog('Frame # {} ({} out of {})'.format( zeroFrame, idx, len(zeroY))).show() print("Completed All Frames")
from ij import IJ from ij.io import SaveDialog from ij.gui import WaitForUserDialog theImage = IJ.getImage() ip = theImage.getProcessor() sd = SaveDialog("Select file to save results","injury",".csv") saveFileName = sd.getFileName() saveFileDir = sd.getDirectory() if (saveFileName is not None): saveFilePath = saveFileDir + saveFileName savefilehandler = open(saveFilePath,"w") waitDialog = WaitForUserDialog("Use freeform tool to outline the piece of tissue") waitDialog.show() roi = theImage.getRoi() if (roi is not None): print type(roi) thePolygon = roi.getPolygon() boundRect = thePolygon.getBounds() for i in range(boundRect.x,boundRect.x+boundRect.width): pos_pixels = 0 tot_pixels = 0 IJ.showProgress(i-boundRect.x,boundRect.width) for j in range(boundRect.y,boundRect.y+boundRect.height): if thePolygon.contains(i,j): value = ip.getPixelValue(i,j) tot_pixels = tot_pixels + 1
imp = IJ.getImage() directory = IJ.getDirectory("image") f = str(imp.getTitle()) date, rows, columns, time_tif = str.split(f) # deconstruct filename time = time_tif.replace('tif','jpg') # need to remove .tif from time row_IDs = list(6*rows[0] + 6*rows[1]) column_IDs = [str(i) for i in 2*(range(int(columns[0]), int(columns[0]) + 6))] zipped = zip(row_IDs, column_IDs) sample_names = ["".join(values) for values in zipped] IJ.setMinAndMax(1900, 11717) # adjust brightness and contrast IJ.run("Apply LUT") IJ.makeRectangle(200, 50, 730, 950) # initialize selection dial = WaitForUserDialog("Adjust selection area") dial.show() # ask user to place selection appropriately IJ.run("Crop") adjDir = os.path.join(directory, "Adjusted") if not os.path.exists(adjDir): os.mkdir(adjDir) adjImage = os.path.join(adjDir, "Adj " + f) IJ.saveAs("Jpeg", adjImage) ## make ROI list w = 130 h = 480 x_vals = 2*[10, 128, 246, 360, 478, 596] y1 = 0 y2 = 470 y_vals = [y1, y1, y1, y1, y1, y1, y2, y2, y2, y2, y2, y2]
ip = FloatProcessor(w, h) pix = ip.getPixels() for x in range(w): for y in range(h): pix[y * w + x] = projected_im_pix[y][x] out_imp = ImagePlus("projected", ip) out_imp.show() egfp_imp_disp.show() roi_stack.show() #egfp_imp_disp.addImageListener(UpdateRoiImageListener(ring_rois)); unwrapped_imp = IJ.createImage("twisted unwrap", 2 * out_imp.getWidth(), out_imp.getHeight(), 1, 32) unwrapped_imp.show() IJ.setTool("freeline") WaitForUserDialog("input unwrap axis").show() unwrap_poly = out_imp.getRoi().getPolygon() unwrap_poly_xs #print("unzip axis = " + str(unzip_axis)); #right_side_xs = unzip_axis; #right_side_xs.append(out_imp.getWidth()); #right_side_xs.append(out_imp.getWidth()); #right_side_ys = [y+1 for y in range(out_imp.getHeight())]; #right_side_ys.append(out_imp.getHeight()); #right_side_ys.append(1); #right_side_roi = PolygonRoi(right_side_xs, right_side_ys, Roi.POLYGON); #out_imp.setRoi(right_side_roi);
def main(): # define here which membrane indices will be used in the analysis, with last index the "control" index membrane_indices = [-1, 0, 1, 3] # for now, work with frontmost open image... imp = IJ.getImage() im_title = imp.getTitle() settings = MembraneEvolutionAnalysisSettings( membrane_indices=membrane_indices) settings.loadPersistedSettings() timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H-%M-%S') DirectoryChooser.setDefaultDirectory((settings.output_path)) dc = DirectoryChooser('Select the root folder for saving output') output_root = dc.getDirectory() if output_root is None: raise IOError('no output path chosen') settings.output_path = output_root # get calibration cal = imp.getCalibration() if cal.getTimeUnit() == "sec": cal.setTimeUnit('s') # pop up a dialog prompting for selection of zero time point, frame interval, and time step for analysis time_steps_not_ok = True while time_steps_not_ok: dialog = NonBlockingGenericDialog("Determine time parameters...") dialog.addNumericField("0 timepoint frame (1-index): ", settings.zero_timepoint_frame, 0) dialog.addNumericField("Acquisition time step (s): ", cal.frameInterval, 2) # assume stored in seconds dialog.addNumericField( "Time step for analysis (s): ", cal.frameInterval * settings.analysis_frame_step, 2) dialog.showDialog() if dialog.wasCanceled(): return zero_f = dialog.getNextNumber() acq_t_step = dialog.getNextNumber() analysis_t_step = dialog.getNextNumber() if acq_t_step != 0 and analysis_t_step != 0: analysis_frame_step = analysis_t_step / acq_t_step if round(analysis_frame_step) == analysis_frame_step: time_steps_not_ok = False settings.zero_timepoint_frame = zero_f settings.analysis_frame_step = analysis_frame_step if time_steps_not_ok: warning_dlg = GenericDialog("Error!") warning_dlg.addMessage( "Analysis time step must be an integer multiple of acquisition time steps, and neither should be zero!!" ) warning_dlg.setOKLabel("Try again...") warning_dlg.showDialog() if warning_dlg.wasCanceled(): return start_frame = int(((zero_f - 1) % analysis_frame_step) + 1) end_frame = int(imp.getNFrames() - (imp.getNFrames() - zero_f) % analysis_frame_step) frames = [ f + 1 for f in range(start_frame - 1, end_frame, int(analysis_frame_step)) ] print("frames = " + str(frames)) imp.killRoi() analysis_imp = SubstackMaker().makeSubstack( imp, str(start_frame) + "-" + str(end_frame) + "-" + str(int(analysis_frame_step))) imp.changes = False imp.close() analysis_imp.show() drawn_membranes = [ TimepointsMembranes(input_image_title=im_title, time_point_s=(t - 1) * acq_t_step) for t in frames ] membranes_listener = UpdateRoiImageListener(drawn_membranes) analysis_imp.addImageListener(membranes_listener) # now attach roi listener to store all 0th membranes after showing a waitforuserdialog to prompt continuation IJ.setTool("freeline") for membrane_idx in membrane_indices: # if membrane_idx>50: # IJ.setTool("line"); analysis_imp.killRoi() membranes_listener.resetLastFrame() membranes_listener.setCurrentMembraneIndex(membrane_idx) analysis_imp.setZ(1) continue_dlg = WaitForUserDialog( "Continue?", "Click OK once all the " + str(membrane_idx) + "-index membranes have been drawn") continue_dlg.show() membranes_listener.imageUpdated(analysis_imp) drawn_membranes = membranes_listener.getDrawnMembraneTimepointsList() json_path = os.path.join(output_root, "Membranes " + timestamp + ".json") f = open(json_path, 'w+') try: json.dump(drawn_membranes, f, default=encode_membrane) finally: f.close() # save csv containing mebrane measurements for current membrane index csv_path = os.path.join( output_root, ("Membrane measurements " + timestamp + ".csv")) if membrane_idx == membrane_indices[0]: try: f = open(csv_path, 'wb') writer = csv.writer(f) writer.writerow([ "Membrane index", ("Time point, " + cal.getTimeUnit()), ("Membrane length, " + cal.getUnit()), ("Euclidean length, " + cal.getUnit()), "Membrane sinuoisty" ]) finally: f.close() try: f = open(csv_path, 'ab') writer = csv.writer(f) for mems in drawn_membranes: mem = mems.getMembrane(membrane_idx) if mem is not None: writer.writerow([ membrane_idx, mems.time_point_s, mem.getPathLength() * cal.pixelWidth, mem.getEuclidean() * cal.pixelWidth, mem.getSinuosity() ]) finally: f.close() settings.persistSettings() settings.save_settings() print("Finished getting all membranes with indices " + str(membrane_indices)) analysis_imp.close()
imp = IJ.openImage(inputDirectory + subfolder + '/' + filename) if imp: # 10X objective IJ.run(imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=" +str(pix_width)+ " pixel_height=" +str(pix_height)+" voxel_depth=25400.0508001") # Change to a GUI option later? # Threshold, fills hole and watershed ic = ImageConverter(imp); ic.convertToGray8(); IJ.setAutoThreshold(imp, "Default dark") if thresholdMode: imp.show() IJ.run("Threshold...") WaitForUserDialog("Title", "Adjust threshold").show() IJ.run(imp, "Convert to Mask", "") if not inverted: IJ.run(imp, "Invert", "") IJ.run(imp, "Fill Holes", "") if watershedMode: IJ.run(imp, "Watershed", "") #Measure particles table = ResultsTable()
return RGBStackMerge.mergeChannels(chimps, False) manders = MandersColocalization() results = ResultsTable() for imageFile in os.listdir(inputDir): print "Opening " + imageFile try: images = BF.openImagePlus(inputDir + imageFile) image = images[0] except UnknownFormatException: continue preview = getPreview(image) preview.show() rm = RoiManager() dialog = WaitForUserDialog("Action required", "Please select regions of interest in this image. Click OK when done.") dialog.show() rm.close() splitter = ChannelSplitter() imp1 = ImagePlus("CH1", splitter.getChannel(image, imageA)) imp2 = ImagePlus("CH2", splitter.getChannel(image, imageB)) title = image.getTitle() title = title[:title.rfind('.')] image.close() preview.close() ch1 = ImagePlusAdapter.wrap(imp1) ch2 = ImagePlusAdapter.wrap(imp2) for roi in rm.getRoisAsArray(): container = createContainer(roi, ch1, ch2) img1 = container.getSourceImage1()
# Finds all the subfolders in the main directory with open(outputDirectory + "annotations_" + name + ".csv", "w") as log: subfolders = [] # for subfolder in os.listdir(inputDirectory): # if os.path.isdir(inputDirectory + subfolder): # subfolders.append(subfolder) # for subfolder in subfolders: for filename in os.listdir(inputDirectory): if filename.endswith(".tif"): imp = IJ.openImage(inputDirectory + filename) imp.show() WaitForUserDialog("Title", "Look at image").show() print("an images was shown") gd = NonBlockingGenericDialog("Channel Options") gd.addStringField( "Enter the frame at which the cells start differentiating: ", "") gd.addStringField( "Enter the frame at which all cells are differentiated: ", "") gd.showDialog() log.write(filename + ',' + gd.getNextString() + ',' + gd.getNextString()) log.write('\n') imp.close()
def main(): # setup Prefs.blackBackground = True params = Parameters() params.load_last_params() # select folders if params.last_input_path is not None: DirectoryChooser.setDefaultDirectory(params.last_input_path) dc = DirectoryChooser("Choose root folder containing data for analysis") input_folder = dc.getDirectory() params.last_input_path = input_folder if input_folder is None: raise KeyboardInterrupt("Run canceled") if params.last_output_path is not None: DirectoryChooser.setDefaultDirectory( os.path.dirname(params.last_output_path)) dc = DirectoryChooser("choose location to save output") output_folder = dc.getDirectory() timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H-%M-%S') output_folder = os.path.join(output_folder, (timestamp + ' output')) params.last_output_path = output_folder os.mkdir(output_folder) analysis_mode = choose_analysis_mode(params) params.last_analysis_mode = analysis_mode params.persist_parameters() # load image(s): files_lst = [ f for f in os.listdir(input_folder) if os.path.splitext(f)[1] == '.tif' ] out_statses = [] for f in files_lst: print("Working on image {}...".format(os.path.splitext(f)[0])) imp = IJ.openImage(os.path.join(input_folder, f)) metadata = import_iq3_metadata( os.path.join(input_folder, os.path.splitext(f)[0] + '.txt')) imp = HyperStackConverter.toHyperStack(imp, 3, imp.getNSlices() // 3, 1, "Color") imp = ZProjector.run(imp, "max") imp.setC(3) IJ.run(imp, "Blue", "") IJ.run(imp, "Enhance Contrast", "saturated=0.35") imp.setC(2) IJ.run(imp, "Red", "") IJ.run(imp, "Enhance Contrast", "saturated=0.35") imp.setC(1) IJ.run(imp, "Green", "") IJ.run(imp, "Enhance Contrast", "saturated=0.35") imp.show() imp.setDisplayMode(IJ.COMPOSITE) cal = imp.getCalibration() cal.setUnit(metadata["y_unit"]) cal.pixelWidth = metadata["x_physical_size"] cal.pixelHeight = metadata["y_physical_size"] imp.setCalibration(cal) if analysis_mode == "GFP intensity": out_stats = gfp_analysis(imp, f, output_folder) elif analysis_mode == "Manual": out_stats = manual_analysis(imp, f, output_folder) out_statses.extend(out_stats) print("Current total number of cells identified: {}".format( len(out_statses))) # get # nuclei per "cell" params.save_parameters_to_json( os.path.join(output_folder, "parameters used.json")) WaitForUserDialog( "Done", "Done, having analysed {} cells in total!".format( len(out_statses))).show() return
for image in os.listdir(inputDirectory): print(image) if "stack" in image: imp = IJ.openImage(inputDirectory + "/" + image) imp2 = IJ.openImage(inputDirectory + "/" + image.replace("stack", "montage")) imp.show() imp2.show() gd = GenericDialog("?") gd.addChoice("Would you like to adjust this one?", ["No", "Yes"], "No") gd.showDialog() if gd.getNextChoice() == "Yes": imp2.close() IJ.run("Brightness/Contrast...") WaitForUserDialog("Title", "Adjust intensities").show() IJ.run("Stack to Images", "") IJ.run(imp, "Merge Channels...", "c2=Green c3=Blue c6=Magenta c7=Yellow create keep") imp = WindowManager.getCurrentImage() IJ.run(imp, "RGB Color", "") IJ.run(imp, "Images to Stack", "name=Stack title=[] use") #WaitForUserDialog("Title", "Now you should have a stack check it out ").show() imp = WindowManager.getCurrentImage() # the Stack imp.show() IJ.setForegroundColor(255, 255, 255) IJ.run( imp, "Make Montage...", "columns=5 rows=1 scale=0.5 borderWidth = 2 useForegroundColor = True" )
from ij import ImageStack, ImagePlus, IJ from ij.gui import WaitForUserDialog, Roi, PolygonRoi from ij.plugin import ChannelSplitter, Straightener, ZProjector # run on imp containing result of tubefitter + IJ.run(imp, "Reslice [/]...", "output=1.000 start=Top avoid") + spline-fitted # manual roi copied from z-projected version of this resliced image (add roi from z-proj to ROI manager, then add # to resliced image) imp.killRoi(); IJ.run(imp, "Reslice [/]...", "output=1.000 start=Top avoid"); rot_imp = IJ.getImage(); crop_roi = Roi(10, 0, rot_imp.getWidth()-20, rot_imp.getHeight()); rot_imp.setRoi(crop_roi); rot_imp.crop(); rot_imp.show(); WaitForUserDialog("pause").show(); split_ch = ChannelSplitter().split(rot_imp); mch_imp = split_ch[0]; egfp_imp = split_ch[1]; roi_imp = split_ch[2]; zproj_imp = ZProjector.run(roi_imp, "max"); IJ.setRawThreshold(zproj_imp, 33153, 65535, None); IJ.run(zproj_imp, "Make Binary", "") zproj_imp.show(); raise error; IJ.run(zproj_imp, "Skeletonize", ""); IJ.run(zproj_imp, "Create Selection", ""); roi = zproj_imp.getRoi(); floatpoly = roi.getContainedFloatPoints(); roi = PolygonRoi(floatpoly, Roi.FREELINE); zproj_imp.setRoi(roi);