def keep_blobs_bigger_than(imp, min_size_pix=100): """remove all blobs other than the largest by area""" imp.killRoi() rt = ResultsTable() if "Size_filtered_" in imp.getTitle(): title_addition = "" else: title_addition = "Size_filtered_" out_imp = IJ.createImage("{}{}".format(title_addition, imp.getTitle()), imp.getWidth(), imp.getHeight(), 1, 8) out_imp.show() IJ.run(out_imp, "Select All", "") IJ.run(out_imp, "Set...", "value=0 slice") mxsz = imp.width * imp.height roim = RoiManager() pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, ParticleAnalyzer.AREA | ParticleAnalyzer.SLICE, rt, min_size_pix, mxsz) pa.setRoiManager(roim) roim.reset() rt.reset() pa.analyze(imp) rt_areas = rt.getColumn(rt.getColumnIndex("Area")).tolist() # print("Number of cells identified: {}".format(len(rt_areas))); for idx in range(len(rt_areas)): roim.select(out_imp, idx) IJ.run(out_imp, "Set...", "value=255 slice") mx_ind = rt_areas.index(max(rt_areas)) roim.reset() roim.close() imp.changes = False imp.close() return out_imp
def keep_largest_blob(imp): """remove all blobs other than the largest by area""" rt = ResultsTable() mxsz = imp.width * imp.height roim = RoiManager(False) pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, ParticleAnalyzer.AREA | ParticleAnalyzer.SLICE, rt, 0, mxsz) pa.setRoiManager(roim) for idx in range(1, imp.getImageStackSize() + 1): roim.reset() rt.reset() imp.setPosition(idx) pa.analyze(imp) rt_areas = rt.getColumn(rt.getColumnIndex("Area")).tolist() mx_ind = rt_areas.index(max(rt_areas)) indices_to_remove = [ a for a in range(0, len(rt_areas)) if a != mx_ind ] indices_to_remove.reverse() for rem_idx in indices_to_remove: roim.select(imp, rem_idx) IJ.run(imp, "Set...", "value=0 slice") imp.killRoi() roim.reset() roim.close()
ParticleAnalyzer.setRoiManager(roim) #Analyses particles: finds all the objects that match criteria pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER | ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES, Measurements.AREA, table, minimum_size, maximum_size, 0.1, 1.0) pa.setHideOutputImage(True) pa.analyze(channel) if thresholdMode: channel.show() WaitForUserDialog("Title", "Look at threshold for" + color[i]).show() #adds count to summary if table.getColumnIndex("Area") != -1: summary[color[i] + "-ROI-count"] = len(table.getColumn(table.getColumnIndex("Area"))) channel.changes = False channel.close() roim.reset() roim.close() # Writes everything in the output file fieldnames = ["Directory", "Filename", "Red-intensity", "Red-threshold-used", "Red-ROI-count", "Green-intensity", "Green-threshold-used", "Green-ROI-count", "Blue-intensity", "Blue-threshold-used", "Blue-ROI-count"] with open(output_name, 'a') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames, extrasaction='ignore', lineterminator = '\n')
def merge_incorrect_splits_and_get_centroids(imp, centroid_distance_limit=100, size_limit=100): """if particles are found with centroids closer than centroid_distance_limit and both have size<size_limit, get average centroid""" imp.killRoi() rt = ResultsTable() out_imp = IJ.createImage("Nuclei centroids from {}".format(imp.getTitle()), imp.getWidth(), imp.getHeight(), 1, 8) out_imp.show() IJ.run(out_imp, "Select All", "") IJ.run(out_imp, "Set...", "value=0 slice") out_imp.show() cal = imp.getCalibration() mxsz = imp.width * cal.pixelWidth * imp.height * cal.pixelHeight print("mxsz = {}".format(mxsz)) roim = RoiManager() imp.show() pa = ParticleAnalyzer( ParticleAnalyzer.ADD_TO_MANAGER, ParticleAnalyzer.AREA | ParticleAnalyzer.SLICE | ParticleAnalyzer.CENTROID, rt, 0, size_limit) pa.setRoiManager(roim) roim.reset() rt.reset() pa.analyze(imp) MyWaitForUser("paise", "pause post-merge incorrect splits particel analysis") rt_xs = rt.getColumn(rt.getColumnIndex("X")).tolist() rt_ys = rt.getColumn(rt.getColumnIndex("Y")).tolist() centroids = [(x, y) for x, y in zip(rt_xs, rt_ys)] print("centroids = {}".format(centroids)) centroids_set = set() for c in centroids: ds = [ math.sqrt((c[0] - cx)**2 + (c[1] - cy)**2) for (cx, cy) in centroids ] close_mask = [d < centroid_distance_limit for d in ds] # if no other centroids are within centroid_distance_limit, add this centroid to the output set # otherwise, add the average position of this centroid and those within centroid_distance_limit to the output set centroids_set.add( (sum([msk * b[0] for msk, b in zip(close_mask, centroids)]) / sum(close_mask), sum([msk * b[1] for msk, b in zip(close_mask, centroids)]) / sum(close_mask))) roim.reset() rt.reset() pa = ParticleAnalyzer( ParticleAnalyzer.ADD_TO_MANAGER, ParticleAnalyzer.AREA | ParticleAnalyzer.SLICE | ParticleAnalyzer.CENTROID, rt, size_limit, mxsz) pa.setRoiManager(roim) pa.analyze(imp) MyWaitForUser("paise", "pause post-merge incorrect splits particel analysis 2") if rt.columnExists("X"): rt_xs = rt.getColumn(rt.getColumnIndex("X")).tolist() rt_ys = rt.getColumn(rt.getColumnIndex("Y")).tolist() centroids = [(x, y) for x, y in zip(rt_xs, rt_ys)] for c in centroids: centroids_set.add(c) centroids = list(centroids_set) cal = imp.getCalibration() centroids = [(c[0] / cal.pixelWidth, c[1] / cal.pixelHeight) for c in centroids] print("new number of nuclei identified = {}".format(len(centroids))) roim.reset() roim.close() for idx, c in enumerate(centroids): roi = OvalRoi(c[0], c[1], 10, 10) out_imp.setRoi(roi) IJ.run(out_imp, "Set...", "value={} slice".format(idx + 1)) imp.changes = False #imp.close(); return out_imp
ParticleAnalyzer.setRoiManager(roim); pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER | ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES, Measurements.AREA | Measurements.FERET | Measurements.CIRCULARITY | Measurements.SHAPE_DESCRIPTORS | Measurements.CENTROID | Measurements.ELLIPSE, table, minimum_size, 9999999999999999, 0.2, 1.0) pa.setHideOutputImage(True) pa.analyze(imp) index = -1 maxArea = -1 if thresholdMode: imp.show() #WaitForUserDialog("Title", "I want to see the ROI").show() # Check if Column even exists (in case it didn't measure anything) if table.getColumnIndex("Area") != -1: # Find the ROI with the largest area for i, area in enumerate(table.getColumn(table.getColumnIndex("Area"))): if area > maxArea: index = i # Writes everything in the output file if index != -1: diameter = 2* math.sqrt( float(table.getValue("Area", index)) / (2* math.pi)) isOrganoid = table.getValue("Area", index) > area_threshold and table.getValue("Area", index) > round_threshold output.write(str(subfolder) + ',' + filename + ',' + str(table.getValue("Feret", index)) + ',' + str(table.getValue("MinFeret", index)) + ',' + str((table.getValue("MinFeret", index)+table.getValue("Feret", index))/2) + ',' + str(table.getValue("Area", index)) + ',' + str(diameter) + ',' + str(table.getValue("Major", index)) + ','+ str(table.getValue("Minor", index)) + ','+ str(table.getValue("Circ.", index)) + ',' +str(table.getValue("Round", index)) + ',' + str(table.getValue("Solidity", index)) + ',' + str(isOrganoid))
def generate_background_rois(input_mask_imp, params, membrane_edges, dilations=5, threshold_method=None, membrane_imp=None): """automatically identify background region based on auto-thresholded image, existing membrane edges and position of midpoint anchor""" if input_mask_imp is None and membrane_imp is not None: segmentation_imp = Duplicator().run(membrane_imp) # do thresholding using either previous method if threhsold_method is None or using (less conservative?) threshold method if (threshold_method is None or not (threshold_method in params.listThresholdMethods())): mask_imp = make_and_clean_binary(segmentation_imp, params.threshold_method) else: mask_imp = make_and_clean_binary(segmentation_imp, threshold_method) segmentation_imp.close() else: input_mask_imp.killRoi() mask_imp = Duplicator().run(input_mask_imp) rois = [] IJ.setForegroundColor(0, 0, 0) roim = RoiManager(True) rt = ResultsTable() for fridx in range(mask_imp.getNFrames()): mask_imp.setT(fridx + 1) # add extra bit to binary mask from loaded membrane in case user refined edges... # flip midpoint anchor across the line joining the two extremes of the membrane, # and fill in the triangle made by this new point and those extremes poly = membrane_edges[fridx].getPolygon() l1 = (poly.xpoints[0], poly.ypoints[0]) l2 = (poly.xpoints[-1], poly.ypoints[-1]) M = (0.5 * (l1[0] + l2[0]), 0.5 * (l1[1] + l2[1])) Mp1 = (params.manual_anchor_midpoint[0][0] - M[0], params.manual_anchor_midpoint[0][1] - M[1]) p2 = (M[0] - Mp1[0], M[1] - Mp1[1]) new_poly_x = list(poly.xpoints) new_poly_x.append(p2[0]) new_poly_y = list(poly.ypoints) new_poly_y.append(p2[1]) mask_imp.setRoi(PolygonRoi(new_poly_x, new_poly_y, PolygonRoi.POLYGON)) IJ.run(mask_imp, "Fill", "slice") mask_imp.killRoi() # now dilate the masked image and identify the unmasked region closest to the midpoint anchor ip = mask_imp.getProcessor() dilations = 5 for d in range(dilations): ip.dilate() ip.invert() mask_imp.setProcessor(ip) mxsz = mask_imp.getWidth() * mask_imp.getHeight() pa = ParticleAnalyzer( ParticleAnalyzer.ADD_TO_MANAGER | ParticleAnalyzer.SHOW_PROGRESS, ParticleAnalyzer.CENTROID, rt, 0, mxsz) pa.setRoiManager(roim) pa.analyze(mask_imp) ds_to_anchor = [ math.sqrt((x - params.manual_anchor_midpoint[0][0])**2 + (y - params.manual_anchor_midpoint[0][1])**2) for x, y in zip( rt.getColumn(rt.getColumnIndex("X")).tolist(), rt.getColumn(rt.getColumnIndex("Y")).tolist()) ] if len(ds_to_anchor) > 0: roi = roim.getRoi(ds_to_anchor.index(min(ds_to_anchor))) rois.append(roi) else: rois.append(None) roim.reset() rt.reset() roim.close() mask_imp.close() return rois
### Compute area fraction of oriented regions ### # Compute area of oriented mask newMaskImp = ImageJFunctions.wrapUnsignedByte(newMask, "New mask"); newMaskImp.getProcessor().setThreshold(1.0, 1.5, False); # [0.5, 1.0] does not work due to rounding problems rt = ResultsTable(); analyzer = Analyzer(newMaskImp, Measurements.AREA | Measurements.LIMIT, rt); analyzer.measure(); # Compute area of overall selection mask energyMaskImp = ImageJFunctions.wrapUnsignedByte(overallSelectionMask, "Energy mask"); energyMaskImp.getProcessor().setThreshold(1.0, 1.5, False); # [0.5, 1.0] does not work due to rounding problems rtEnergy = ResultsTable(); analyzerEnergy = Analyzer(energyMaskImp, Measurements.AREA | Measurements.LIMIT, rtEnergy); analyzerEnergy.measure(); # Print Area% (through SciJava OUTPUT, see L5) if IJ.debugMode: print("Coherency area: "+str(rt.getValueAsDouble(rt.getColumnIndex("Area"), rt.size()-1))); print("Energy area: "+str(rtEnergy.getValueAsDouble(rtEnergy.getColumnIndex("Area"), rtEnergy.size()-1))); areaCoherency = rt.getValueAsDouble(rt.getColumnIndex("Area"), rt.size()-1); areaEnergy = rtEnergy.getValueAsDouble(rtEnergy.getColumnIndex("Area"), rtEnergy.size()-1); areaFraction = str(areaCoherency/areaEnergy*100.0)+"%"; # Close "S-Mask" if not IJ.debugMode: maskImp.close(); # Close "Energy" if not IJ.debugMode and useEnergy: energyImp.close();
keep_rois = []; pa.analyze(imp); IJ.run("Set Measurements...", "centroid redirect=None decimal=3"); frames = imp.getNFrames(); for fridx in range(0, frames): rt.reset(); imp.setSliceWithoutUpdate(fridx + 1); ip = imp.getProcessor(); if not pa.analyze(imp, ip): raise Exception("something went wrong analysing particles!") rt.show("centroids"); rm = RoiManager.getInstance(); if rm.getCount() > 0: rois = rm.getRoisAsArray(); centroidsx = rt.getColumn(rt.getColumnIndex('X')); centroidsy = rt.getColumn(rt.getColumnIndex('Y')); print(centroidsx); print(centroidsy); gd = GenericDialog("Continue?"); gd.showDialog(); if gd.wasCanceled(): raise Exception("Run interupted"); for roi in rois: imp.setRoi(roi); stats = ImageStatistics().getStatistics(ip); print(stats.xCenterOfMass) #print(keep_rois)
# FINDS THE TISSUE AREA img2 = imp.duplicate() channels2=ChannelSplitter.split(img2); redimg2=channels2[0]; IJ.run(redimg2, "8-bit", ""); IJ.setAutoThreshold(redimg2, "Default dark"); IJ.setThreshold(redimg2,20, 254); IJ.run(redimg2, "Convert to Mask", ""); redimg2.show() time.sleep(1) rt2 = ResultsTable() ta=Analyzer(redimg2,Measurements.AREA|Measurements.LIMIT,rt2) ta.measure(); double=rt2.getColumnAsDoubles(rt2.getColumnIndex("Area")) summary["Tissue-area"] =double[0]; redimg2.changes = False redimg2.close() # PARTICLE ANALYSIS ETC.. channels = ChannelSplitter.split(imp); for i, channel in enumerate(channels): IJ.setAutoThreshold(channel,"Default"); summary[color[i] + "-intensity"] = "NA" summary[color[i] + "-ROI-count"] = "NA"
table = ResultsTable() pa = ParticleAnalyzer( ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES, Measurements.AREA | Measurements.FERET | Measurements.CIRCULARITY | Measurements.SHAPE_DESCRIPTORS | Measurements.CENTROID | Measurements.ELLIPSE, table, minimum_size, 9999999999999999, 0.1, 1.0) pa.setHideOutputImage(True) pa.analyze(imp) index = -1 maxArea = -1 # Check if Column even exists (in case it didn't measure anything) if table.getColumnIndex("Area") != -1: # Find the ROI with the largest area for i, area in enumerate( table.getColumn(table.getColumnIndex("Area"))): if area > maxArea: index = i if thresholdMode: imp.show() # Writes everything in the output file if index != -1: diameter = 2 * math.sqrt(
print invertedDict if imageOrTable == "Results table": rt = ResultsTable.getResultsTable(resultsName).clone() else: measureImp=WM.getImage(imageName) src2=clij2.push(measureImp) rt = ResultsTable() clij2.statisticsOfBackgroundAndLabelledPixels(src2, test.src,rt) src2.close() resultsName="Results table" try: labels = rt.getColumn(rt.getColumnIndex('TrackID')) frame = rt.getColumn(rt.getColumnIndex('Frame (Time)')) except: try: labels = rt.getColumn(rt.getColumnIndex('Label')) except: labels = rt.getColumn(rt.getColumnIndex('IDENTIFIER')) for i in range(len(labels)): try: rt.setValue("Label name", i,listOfNames[int(labels[i])]) rt.setValue("Label value", i,invertedDict[int(labels[i])]) except: print i
def analyze(iDataSet, tbModel, p, output_folder): # # LOAD FILES # filepath = tbModel.getFileAPth(iDataSet, "RAW", "IMG") filename = tbModel.getFileName(iDataSet, "RAW", "IMG") print("Analyzing: "+filepath) IJ.run("Bio-Formats Importer", "open=["+filepath+"] color_mode=Default view=Hyperstack stack_order=XYCZT"); imp = IJ.getImage() # # INIT # IJ.run("Options...", "iterations=1 count=1"); # # SCALING # IJ.run(imp, "Scale...", "x="+str(p["scale"])+" y="+str(p["scale"])+" z=1.0 interpolation=Bilinear average process create"); imp = IJ.getImage() # save output file output_file = filename+"--downscale_input.tif" IJ.saveAs(IJ.getImage(), "TIFF", os.path.join(output_folder, output_file)) tbModel.setFileAPth(output_folder, output_file, iDataSet, "INPUT","IMG") # # CONVERSION # #IJ.run(imp, "8-bit", ""); # # CROPPING # #imp.setRoi(392,386,750,762); #IJ.run(imp, "Crop", ""); # # BACKGROUND SUBTRACTION # # IJ.run(imp, "Subtract...", "value=32768 stack"); IJ.run(imp, "Z Project...", "projection=[Average Intensity]"); imp_avg = IJ.getImage() ic = ImageCalculator(); imp = ic.run("Subtract create 32-bit stack", imp, imp_avg); # # REGION SEGMENTATION # imp1 = Duplicator().run(imp, 1, imp.getImageStackSize()-1) imp2 = Duplicator().run(imp, 2, imp.getImageStackSize()) imp_diff = ic.run("Subtract create 32-bit stack", imp1, imp2); #imp_diff.show() IJ.run(imp_diff, "Z Project...", "projection=[Standard Deviation]"); imp_diff_sd = IJ.getImage() # save IJ.run(imp_diff_sd, "Gaussian Blur...", "sigma=5"); output_file = filename+"--sd.tif" IJ.saveAs(imp_diff_sd, "TIFF", os.path.join(output_folder, output_file)) tbModel.setFileAPth(output_folder, output_file, iDataSet, "SD","IMG") IJ.run(imp_diff_sd, "Enhance Contrast", "saturated=0.35"); IJ.run(imp_diff_sd, "8-bit", ""); IJ.run(imp_diff_sd, "Properties...", "unit=p pixel_width=1 pixel_height=1 voxel_depth=1"); IJ.run(imp_diff_sd, "Auto Local Threshold", "method=Niblack radius=60 parameter_1=2 parameter_2=0 white"); rm = ROIManipulator.getEmptyRm() IJ.run(imp_diff_sd, "Analyze Particles...", "add"); # select N largest Rois diameter_roi = [] for i in range(rm.getCount()): roi = rm.getRoi(i) diameter_roi.append([roi.getFeretsDiameter(), roi]) diameter_roi = sorted(diameter_roi, reverse=True) #print diameter_roi rm.reset() for i in range(min(len(diameter_roi), p["n_rois"])): rm.addRoi(diameter_roi[i][1]) # save output_file = filename+"--rois" ROIManipulator.svRoisToFl(output_folder, output_file, rm.getRoisAsArray()) tbModel.setFileAPth(output_folder, output_file+".zip", iDataSet, "REGIONS","ROI") # # FFT in each region # IJ.run(imp, "Variance...", "radius=2 stack"); output_file = filename+"--beats.tif" IJ.saveAs(imp, "TIFF", os.path.join(output_folder, output_file)) tbModel.setFileAPth(output_folder, output_file, iDataSet, "BEATS","IMG") n = rm.getCount() for i_roi in range(n): imp_selection = Duplicator().run(imp) rm.select(imp_selection, i_roi) IJ.run(imp_selection, "Clear Outside", "stack"); imp_selection.show() # FFT using Parallel FFTJ transformer = FloatTransformer(imp_selection.getStack()) transformer.fft() imp_fft = transformer.toImagePlus(SpectrumType.FREQUENCY_SPECTRUM) imp_fft.show() # Analyze FFt IJ.run(imp_fft, "Gaussian Blur 3D...", "x=0 y=0 z=1.5"); IJ.run(imp_fft, "Plot Z-axis Profile", ""); output_file = filename+"--Region"+str(i_roi+1)+"--fft.tif" IJ.saveAs(IJ.getImage(), "TIFF", os.path.join(output_folder, output_file)) tbModel.setFileAPth(output_folder, output_file, iDataSet, "FFT_R"+str(i_roi+1),"IMG") IJ.run(imp_fft, "Select All", ""); rm.addRoi(imp_fft.getRoi()) rm.select(rm.getCount()) rt = ResultsTable() rt = rm.multiMeasure(imp_fft); #print(rt.getColumnHeadings); x = rt.getColumn(rt.getColumnIndex("Mean1")) #rm.runCommand("delete") peak_height_pos = [] x_min = 10 for i in range(x_min,len(x)/2): before = x[i-1] center = x[i] after = x[i+1] if (center>before) and (center>after): peak_height_pos.append([float(x[i]),i]) if len(peak_height_pos)>0: peak_height_pos = sorted(peak_height_pos, reverse=True) n_max = 3 for i_max in range(min(len(peak_height_pos),n_max)): tbModel.setNumVal(round(float(len(x))/float(peak_height_pos[i_max][1]),2), iDataSet, "F"+str(i_max+1)+"_R"+str(i_roi+1)) tbModel.setNumVal(int(peak_height_pos[i_max][0]), iDataSet, "A"+str(i_max+1)+"_R"+str(i_roi+1))
def procOneImage(pathpre, wnumber, endings): """ Analyzes a single image set (Dapi, VSVG, PM images) pathpre: fullpath prefix, down till "endings". endings: a dictionary with signiture for three different channels. wnumber: a number in string, indicating the spot ID. Returns three results tables. """ imp = IJ.openImage(pathpre + endings['dapi'] + '.tif') impVSVG = IJ.openImage(pathpre + endings['vsvg'] + '.tif') impPM = IJ.openImage(pathpre + endings['pm'] + '.tif') imp2 = imp.duplicate() rtallcellPM = ResultsTable() rtjnucVSVG = ResultsTable() rtallcellVSVG = ResultsTable() backVSVG = backgroundSubtraction(impVSVG) backPM = backgroundSubtraction(impPM) impfilteredNuc = nucleusSegmentation(imp2) intmax = impfilteredNuc.getProcessor().getMax() if intmax == 0: return rtallcellPM, rtjnucVSVG, rtallcellVSVG impfilteredNuc.getProcessor().setThreshold(1, intmax, ImageProcessor.NO_LUT_UPDATE) nucroi = ThresholdToSelection().convert(impfilteredNuc.getProcessor()) nucroiA = ShapeRoi(nucroi).getRois() #print nucroiA allcellA = [roiEnlarger(r) for r in nucroiA] jnucroiA = [roiRingGenerator(r) for r in nucroiA] #print allcellA print 'Detected Cells: ', len(jnucroiA) if len(jnucroiA) <2: print "measurement omitted, as there is only on nucleus detected" return rtallcellPM, rtjnucVSVG, rtallcellVSVG if (GUIMODE): rm = RoiManager() for r in jnucroiA: rm.addRoi(r) rm.show() impfilteredNuc.show() measOpt = PA.AREA + PA.MEAN + PA.CENTROID + PA.STD_DEV + PA.SHAPE_DESCRIPTORS + PA.INTEGRATED_DENSITY + PA.MIN_MAX +\ PA.SKEWNESS + PA.KURTOSIS + PA.MEDIAN + PA.MODE ## All Cell Plasma Membrane intensity measureROIs(impPM, measOpt, rtallcellPM, allcellA, backPM, True) meanInt_Cell = rtallcellPM.getColumn(rtallcellPM.getColumnIndex('Mean')) print "Results Table rownumber:", len(meanInt_Cell) # JuxtaNuclear VSVG intensity measureROIs(impVSVG, measOpt, rtjnucVSVG, jnucroiA, backVSVG, False) meanInt_jnuc = rtjnucVSVG.getColumn(rtjnucVSVG.getColumnIndex('Mean')) # AllCell VSVG intensity measureROIs(impVSVG, measOpt, rtallcellVSVG, allcellA, backVSVG, True) meanInt_vsvgall = rtallcellVSVG.getColumn(rtallcellVSVG.getColumnIndex('Mean')) #Calculation of Transport Ratio JuxtaNuclear VSVG intensity / All Cell Plasma Membrane intensity results will be appended to PM results table. for i in range(len(meanInt_Cell)): if meanInt_Cell[i] != 0.0: transportR = meanInt_jnuc[i] / meanInt_Cell[i] transportRall = meanInt_vsvgall[i] / meanInt_Cell[i] else: transportR = float('inf') transportRall = float('inf') rtjnucVSVG.setValue('TransportRatio', i, transportR) rtallcellVSVG.setValue('TransportRatio', i, transportRall) rtjnucVSVG.setValue('WellNumber', i, int(wnumber)) rtallcellVSVG.setValue('WellNumber', i, int(wnumber)) rtallcellPM.setValue('WellNumber', i, int(wnumber)) return rtallcellPM, rtjnucVSVG, rtallcellVSVG
def nucleusSegmentation(imp2): """ Segmentation of nucleus image. Nucleus are selected that: 1. No overlapping with dilated regions 2. close to circular shape. Deformed nuclei are rejected. Outputs a binary image. """ #Convert to 8bit ImageConverter(imp2).convertToGray8() #blur slightly using Gaussian Blur radius = 2.0 accuracy = 0.01 GaussianBlur().blurGaussian( imp2.getProcessor(), radius, radius, accuracy) # Auto Local Thresholding imps = ALT().exec(imp2, "Bernsen", 15, 0, 0, True) imp2 = imps[0] #ParticleAnalysis 0: prefiltering by size and circularity rt = ResultsTable() paOpt = PA.CLEAR_WORKSHEET +\ PA.SHOW_MASKS +\ PA.EXCLUDE_EDGE_PARTICLES +\ PA.INCLUDE_HOLES #+ \ # PA.SHOW_RESULTS measOpt = PA.AREA + PA.STD_DEV + PA.SHAPE_DESCRIPTORS + PA.INTEGRATED_DENSITY MINSIZE = 20 MAXSIZE = 10000 pa0 = PA(paOpt, measOpt, rt, MINSIZE, MAXSIZE, 0.8, 1.0) pa0.setHideOutputImage(True) pa0.analyze(imp2) imp2 = pa0.getOutputImage() # Overwrite imp2.getProcessor().invertLut() #impNuc = imp2.duplicate() ## for the ring. impNuc = Duplicator().run(imp2) #Dilate the Nucleus Area ## this should be 40 pixels in Cihan's method, but should be smaller. #for i in range(20): # IJ.run(imp2, "Dilate", "") rf = RankFilters() rf.rank(imp2.getProcessor(), RIMSIZE, RankFilters.MAX) #Particle Analysis 1: get distribution of sizes. paOpt = PA.CLEAR_WORKSHEET +\ PA.SHOW_NONE +\ PA.EXCLUDE_EDGE_PARTICLES +\ PA.INCLUDE_HOLES #+ \ # PA.SHOW_RESULTS measOpt = PA.AREA + PA.STD_DEV + PA.SHAPE_DESCRIPTORS + PA.INTEGRATED_DENSITY rt1 = ResultsTable() MINSIZE = 20 MAXSIZE = 10000 pa = PA(paOpt, measOpt, rt1, MINSIZE, MAXSIZE) pa.analyze(imp2) #rt.show('after PA 1') #particle Analysis 2: filter nucleus by size and circularity. #print rt1.getHeadings() if (rt1.getColumnIndex('Area') > -1): q1, q3, outlier_offset = getOutlierBound(rt1) else: q1 = MINSIZE q3 = MAXSIZE outlier_offset = 0 print imp2.getTitle(), ": no Nucleus segmented,probably too many overlaps" paOpt = PA.CLEAR_WORKSHEET +\ PA.SHOW_MASKS +\ PA.EXCLUDE_EDGE_PARTICLES +\ PA.INCLUDE_HOLES #+ \ # PA.SHOW_RESULTS rt2 = ResultsTable() #pa = PA(paOpt, measOpt, rt, q1-outlier_offset, q3+outlier_offset, circq1-circoutlier_offset, circq3+circoutlier_offset) pa = PA(paOpt, measOpt, rt2, q1-outlier_offset, q3+outlier_offset, 0.8, 1.0) pa.setHideOutputImage(True) pa.analyze(imp2) impDilatedNuc = pa.getOutputImage() #filter original nucleus filteredNuc = ImageCalculator().run("AND create", impDilatedNuc, impNuc) return filteredNuc