def calculateCostsOneLevel(self, level=1, previousCandidates=None, bestScore=3.1): print("Calculating Costs of Path with depth " + str(level)) # Create the PathList of Level level (pathLists, innateCosts, overlapCosts, leftoverCosts) = self.generatePathLists(level, previousCandidates, bestScore) table = ResultsTable() minTotalCost = 3 for pathListIndex, pathList in enumerate(pathLists, start=0): totalCost = (innateCosts[pathListIndex] + overlapCosts[pathListIndex] + leftoverCosts[pathListIndex]) minTotalCost = min(totalCost, minTotalCost) for pathIndex, path in enumerate(pathList): table.setValue("Path " + str(pathIndex), pathListIndex, "P-" + str(path.getID())) table.setValue("Innate Cost", pathListIndex, innateCosts[pathListIndex]) table.setValue("Overlap Cost", pathListIndex, overlapCosts[pathListIndex]) table.setValue("Leftover Cost", pathListIndex, leftoverCosts[pathListIndex]) table.setValue("Total Cost", pathListIndex, totalCost) table.show("Costs for Level " + str(level)) return (pathLists, minTotalCost)
def calculateRipley(tableName1,tableName2,volume,radiusMax=2,nbSteps=20): pointsA = pointList3DFromRT(tableName1) pointsB = pointList3DFromRT(tableName2) table = ResultsTable() step = float(radiusMax) / nbSteps idx = 0 IJ.log("Radius Max = "+str(radiusMax)) IJ.log("Step = "+str(step)) nbPoints = len(pointsA+pointsB) density = float(nbPoints)/float(volume) print(str(density)) #density = getDensity(pointsA,pointsB) #nbPoints = len(pointsA+pointsB) for i in range(1,nbSteps+1): radius = i*step table.setValue("Radius",idx,radius) count = countPointsCloser(pointsA,pointsB,radius) table.setValue("Count",idx,count) K = count/(density*nbPoints) table.setValue("Ripley's K",idx,K) expected = (4/3) * math.pi * radius * radius * radius table.setValue("Expected Ripley's K",idx,expected) table.setValue("Ripley's L",idx,pow(K/math.pi,1./3)-radius) idx = idx+1 table.show("Ripley's Table")
def pixel_collector(rm, channel_imp, channel_name, impname, folder): # define new Results table rt = ResultsTable() IndRois = rm.getIndexes() for index in IndRois: ROI = rm.getRoi(index) ROI_name = ROI.getName() coords = ROI.getContainedPoints() row = 0 for pixel in coords: x_coord = pixel.getX() y_coord = pixel.getY() rt.setValue(ROI_name + "_X_pos", row, int(x_coord)) rt.setValue(ROI_name + "_Y_pos", row, int(y_coord)) pixel_2 = channel_imp.getProcessor().getPixel( int(x_coord), int(y_coord)) rt.setValue(ROI_name + "_" + channel_name, row, pixel_2) row = row + 1 rt.show("Results") rt.save(os.path.join(folder, impname + '_' + channel_name + "_pixels.csv")) print "Pixel collection done!"
def showClassSummary(table): resClass=dict() resTable=ResultsTable() for i,d in table.items(): curClass=d['Class'] resClass.setdefault(curClass,[]).append(i) resClassName=sorted(resClass.keys()) for i,clsName in enumerate(resClassName): resTable.setValue('Class',i,clsName) resTable.setValue('Counts',i,len(resClass[clsName])) resTable.show('[Class Summary]'+imgName)
def reportClustersAsTable(clusters, allPoints, XColumn='X', YColumn='Y', ZColumn='Z', NRColumn='NR'): ''' Report the clustered and unclustered points in the tables 'clusters' and 'unclustered'. ''' rt = ResultsTable() counter = 1 clusterCounter = 1 clusteredPoints = [] for c in clusters: for dp in c.getPoints(): rt.incrementCounter() p = dp.getPoint() rt.addValue(NRColumn, counter) rt.addValue(XColumn, p[0]) rt.addValue(YColumn, p[1]) rt.addValue(ZColumn, p[2]) rt.addValue("C", clusterCounter) counter = counter + 1 clusteredPoints.append([p[0], p[1], p[2]]) clusterCounter = clusterCounter + 1 rt.show("clusters") win = WindowManager.getWindow("Results") rt = win.getResultsTable() X, Y, Z = getColumns(XColumn, YColumn, ZColumn) if not rt.columnExists(NRColumn): for i in range(0, len(X)): rt.setValue(NRColumn, i, i + 1) rt.updateResults() NR = getColumn(NRColumn) unclusteredPoints = [ [point.getPoint()[0], point.getPoint()[1], point.getPoint()[2]] for point in allPoints if [point.getPoint()[0], point.getPoint()[1], point.getPoint()[2]] not in clusteredPoints ] counter = 1 rt = ResultsTable() for p in unclusteredPoints: rt.incrementCounter() rt.addValue(NRColumn, counter) rt.addValue(XColumn, p[0]) rt.addValue(YColumn, p[1]) rt.addValue(ZColumn, p[2]) counter = counter + 1 rt.show("unclustered") WindowManager.setWindow(win)
def copyMatrixToRt2D(matrix,tableName="Results",sizeX=-1,sizeY=-1,useFirstRowAsHeader=False): if sizeX == -1: sizeX = len(matrix) if sizeY == -1: sizeY = len(matrix[0]) table = ResultsTable() for indexX in range(sizeX): for indexY in range(sizeY): if useFirstRowAsHeader: if indexY == 0: continue table.setValue(str(matrix[indexX][0]),indexY-1,matrix[indexX][indexY]) else: table.setValue(indexX,indexY,matrix[indexX][indexY]) table.show(tableName)
def showRoiSummary(table): res=ResultsTable() for i,val in table.items(): res.setValue('id',i,i+1) valInd=val.keys() valInd.remove('Class') for ind in valInd: res.setValue(ind,i,val[ind]) res.setValue('Class',i,val['Class']) res.show('[ROI Summary]'+imgName)
def cellSegmentation(srcDir, dstDir, currentDir, filename, keepDirectories): print "Processing:" # Opening the image print "Open image file", filename imp = IJ.openImage(os.path.join(currentDir, dstDir)) # Put your processing commands here! localinput=srcDir.replace("/", "\\") saveDir = localinput.replace(srcDir, dstDir) string="." dotIndex=filename.find(string) localfile= filename[0:dotIndex] print(localfile) IJ.run("New... ", "name="+f+" type=Table") print(f,"\\Headings:Cell\tarea\tCirc\tAR\tRoundness\tMaximum") IJ.run("Bio-Formats", "open=[" + localinput + os.path.sep + filename +"] autoscale color_mode=Default rois_import=[ROI manager] view=Hyperstack stack_order=XYCZT") IJ.open() idd= WM.getIDList(); imageID= idd[0]; IJ.run("Clear Results") WM.getImage(imageID) IJ.run("Duplicate...", "duplicate channels="+str(x)+"") #Nucleus channel #took away x IJ.run("Z Project...", "projection=[Standard Deviation]");#picture for frame detection IJ.run("8-bit"); IJ.run("Duplicate...", "title=IMAGE");#frame IJ.run("Duplicate...", "title=SUBTRACT");#Background subtraction mask (for frame and watershed) imp=IJ.getImage() pixelWidth=imp.getWidth() pixelWidth=pixelWidth/1647.89 pixelHeight= imp.getHeight() #create subtraction mask, applying constraining maximum (step I) IJ.selectWindow("SUBTRACT") nResults=imp.getStatistics() row = nResults rt_exist = WM.getWindow("Results") if rt_exist==None: rt= ResultsTable() else: rt = rt_exist.getTextPanel().getOrCreateResultsTable() rt.setValue("Max ", 0, row.max) #text file rt.show("Results") u=math.floor(row.mean*3) IJ.run("Max...","value="+str(u)) #constraining maximum of 3-fold mean to reduce effect of extreme values during subtraction #gaussian blurring (step II) IJ.run("Gaussian Blur...", "sigma=100 scaled") #blurring for subtraction mask IJ.selectWindow("IMAGE") pxrollrad = cellradius/pixelWidth; #rolling ball radius in pixels needed (= predefined cell radius[µm]/pixelsize[µm/px]) IJ.run("Subtract Background...", "rolling="+str(pxrollrad)+"") IJ.run("Gaussian Blur...", "sigma=2 scaled") #reduces punctate character of grayscale image ' IM=IJ.selectWindow("IMAGE") SUB=IJ.selectWindow("SUBTRACT") ic().run("SUBTRACT", IM, SUB) #just subtracts two images IJ.selectWindow("IMAGE") #see how to call IJ.run("Duplicate...", "title=AND")#watershed IJ.run("Duplicate...", "title=CHECK")#for checking if maxima exist within selection later #Apply threshold to get binary image of cell borders (step IV) IJ.selectWindow("IMAGE") imp = IJ.getImage() # the current image imp.getProcessor().setThreshold(1, 255, ImageProcessor.NO_LUT_UPDATE) IJ.run("Subtract Background...","...") IJ.run("Convert to Mask", "method=Default background=Dark only black") IJ.run("Fill Holes") #Create watershed line image (step V) IJ.selectWindow("AND") IJ.run("Gaussian Blur...", "sigma=2 scaled") imp=IJ.getImage() pixelWidth=imp.getWidth() pixelWidth=pixelWidth/1647.89 pixelHeight= imp.getHeight() # Saving the image nResults=imp.getStatistics() row = nResults rt.setValue("Max ", 1, row.max) #text file nBins = 256 Hist = HistogramWindow("Histogram",imp,nBins) Table = Hist.getResultsTable() Counts = Table.getColumn(1) #mean gray value of pixels belonging to cells needed (i.e. mean of ONLY non-zero pixel) Sum = 0 #all counts CV = 0 #weighed counts (= counts * intensity) for i in range(0, len(Counts)): #starting with 1 instead of 0. -> 0 intensity values are not considered. Sum += Counts[i] CV += Counts[i]*i m = (CV/Sum) m=math.floor(m) l = math.floor(2*m) #Maxima need to be at least twice the intensity of cellular mean intensity IJ.run("Find Maxima...", "noise="+str(l)+" output=[Segmented Particles] exclude") #watershedding #Combine watershed lines and cell frame (step VI) IJ.selectWindow("IMAGE") imp=IJ.getImage() imp.getProcessor().setThreshold(1, 255, ImageProcessor.NO_LUT_UPDATE) IJ.run(imp, "Watershed", "") #useful imp = IJ.getImage() ip = imp.getProcessor() segip = MaximumFinder().findMaxima( ip, 1, ImageProcessor.NO_THRESHOLD, MaximumFinder.SEGMENTED , False, False) segip.invert() segimp = ImagePlus("seg", segip) segimp.show() mergeimp = RGBStackMerge.mergeChannels(array([segimp, None, None, imp, None, None, None], ImagePlus), True) mergeimp.show() pa_exist = WM.getWindow("Results for PA") if pa_exist==None: pa_rt= ResultsTable() else: pa_rt = pa_exist.getTextPanel().getOrCreateResultsTable() ParticleAnalyzer.setResultsTable(pa_rt) IJ.run("Set Measurements...", "area mean perimeter shape decimal=3") IJ.run("Analyze Particles...", "size=" + str(cellradius) + "-Infinity circularity=0.1-1.00 add"); #Cell bodies detected pa_rt.show("Results for PA ") save_all(srcDir, dstDir, filename, localfile, keepDirectories, imageID)
rowNumber = 0 for spot in sortedTrack: 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') std = spot.getFeature('STANDARD_DEVIATION') estdia = spot.getFeature('ESTIMATED_DIAMETER') 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)) table.setValue("TRACK_ID", rowNumber, id) table.setValue("POSITION_X", rowNumber, x) table.setValue("POSITION_Y", rowNumber, y) table.setValue("FRAME", rowNumber, t) table.setValue("MEAN_INTENSITY", rowNumber, mean) table.setValue("STANDARD_DEVIATION", rowNumber, std) table.setValue("SNR", rowNumber, snr) rowNumber = rowNumber + 1 # roi1 = PointRoi(x/dx, y/dy) # roi1.setPosition(int(t)) # rm.add(imp, roi1, nextRoi) # nextRoi = nextRoi+1 frame = table.getColumn(3) mean = table.getColumn(4)
thr1, thrimp1 = calculateThreshold(imp1, roi, methods[0]) thr2, thrimp2 = calculateThreshold(imp2, roi, methods[1]) cursor = TwinCursor(img1.randomAccess(), img2.randomAccess(), Views.iterable(mask).localizingCursor()) rtype = img1.randomAccess().get().createVariable() raw = manders.calculateMandersCorrelation(cursor, rtype) rthr1 = rtype.copy() rthr2 = rtype.copy() rthr1.set(thr1) rthr2.set(thr2) cursor.reset() thrd = manders.calculateMandersCorrelation(cursor, rthr1, rthr2, ThresholdMode.Above) print "Results are: %f %f %f %f" % (raw.m1, raw.m2, thrd.m1, thrd.m2) results.incrementCounter() rowno = results.getCounter() - 1 results.setValue("Cell", rowno, int(rowno)) results.setValue("Threshold 1", rowno, int(thr1)) results.setValue("Threshold 2", rowno, int(thr2)) results.setValue("M1 raw", rowno, float(raw.m1)) results.setValue("M2 raw", rowno, float(raw.m2)) results.setValue("M1 thrd", rowno, float(thrd.m1)) results.setValue("M2 thrd", rowno, float(thrd.m2)) thrimp = RGBStackMerge.mergeChannels([thrimp1, thrimp2], False) saver = FileSaver(thrimp) saver.saveAsTiffStack(outputDir + "Cell_%i-" % results.getCounter() + title + ".tif") thrimp.close() results.show("Colocalization results")
ol.add(gfp) gfpMean = gfpSum / gfpA if gfpA > 0 else 0 row = rt.getCounter() uni = row % 26 cha = chr(ord('A') + uni) name = "" while len(name) < (row + 1) / 26.0: name += cha label = TextRoi(name, cXbf - 20, cYbf + 20, FONT) label.setStrokeColor(Color.GREEN) label.setPosition(0, z, 1) ol.add(label) rt.setValue("Organoid", row, name) rt.setValue("X", row, cXbf * cal.pixelWidth) rt.setValue("Y", row, cYbf * cal.pixelHeight) rt.setValue("Area", row, roiStatsBF.area * cal.pixelWidth * cal.pixelHeight) rt.setValue("Contained Tomato Area", row, tomatoA * cal.pixelWidth * cal.pixelHeight) rt.setValue("Contained GFP Area", row, gfpA * cal.pixelWidth * cal.pixelHeight) rt.setValue("Contained GFP Mean", row, gfpMean) imp.setOverlay(ol) rt.show(imp.getTitle() + "_Z" + str(z) + "_Results")
def create_plot(imp, method, average, threshold=0.1): intensity = cross_section_intensity(imp, method) cal = imp.getCalibration() x_inc = cal.pixelWidth; units = cal.getUnits(); x_label = "Distance (%s)" % units y_label = 'Intensity' # cal.getValueUnit() x_values = [i*x_inc for i in range(len(intensity))] lastindex = len(x_values)-1 for i in range(1, len(x_values)+1): index = len(x_values)-i if intensity[index] == 0: lastindex = index-1 else: break ax = [x_values[i] for i in range(lastindex)] ay = [intensity[i] for i in range(lastindex)] average_x, average_y = rolling_average(ax, ay, average) firstidx, lastidx, threshold_intensity = get_thresholded_idx(average_y, threshold=threshold) perform_trim = firstidx!=-1 and lastidx!=-1 if perform_trim: trim_x = [average_x[i] for i in range(firstidx, lastidx+1)] trim_y = [average_y[i] for i in range(firstidx, lastidx+1)] # raw data flags = Plot.getDefaultFlags() flags = flags - Plot.Y_GRID - Plot.X_GRID plot = Plot("%s-Plot" % imp.getTitle(), x_label, y_label, flags) plot.setLineWidth(1) plot.setColor(Color.BLACK) plot.addPoints(x_values, intensity,Plot.LINE) # threshold line plot.setLineWidth(2) plot.setColor(Color.BLACK) plot.addPoints([0,x_inc * imp.getWidth()], [threshold_intensity,threshold_intensity],Plot.LINE) # rolling average plot.setLineWidth(2) plot.setColor(Color.MAGENTA) plot.addPoints(average_x,average_y,Plot.LINE) # standard legend labels labels = "\t".join(['Raw Data (%s)' % method, 'Intensity threshold (%d%s)' % (100*threshold, '%'), 'Rolling Average (n=%d)' % average]) # trimmed rolling average if perform_trim: plot.setLineWidth(2) plot.setColor(Color.GREEN) plot.addPoints(trim_x,trim_y,Plot.LINE) labels+='\tTrimmed Rolling Average (n=%d)' % average plot.setColor(Color.BLACK) plot.setLimitsToFit(False) plot.addLegend(labels) rt = ResultsTable() for row,x in enumerate(x_values): rt.setValue(DIST_RAW_COL, row, x) rt.setValue(INT_RAW_COL, row, intensity[row]) for row,x in enumerate(average_x): rt.setValue(DIST_AVG_COL, row, x) rt.setValue(INT_AVG_COL, row, average_y[row]) if perform_trim: for row,x in enumerate(trim_x): rt.setValue(DIST_TRIM_COL, row, x) rt.setValue(INT_TRIM_COL, row, trim_y[row]) return plot, rt
def measure(stack, cells, nuclei): time = [ (t-1)*cal.frameInterval for t in range(T+1) ] cellValues0 = [ 0.0 for t in range(T+1) ] cellValues1 = [ 0.0 for t in range(T+1) ] cellAreas0 = [ 0.0 for t in range(T+1) ] cellAreas1 = [ 0.0 for t in range(T+1) ] nucleusValues0 = [ 0.0 for t in range(T+1) ] nucleusValues1 = [ 0.0 for t in range(T+1) ] nucleusAreas0 = [ 0.0 for t in range(T+1) ] nucleusAreas1 = [ 0.0 for t in range(T+1) ] nonNucleusValues0 = [ 0.0 for t in range(T+1) ] nonNucleusValues1 = [ 0.0 for t in range(T+1) ] for t in range(1,T+1): ip = stack.getProcessor(t) if cells[t] is None: continue #subtract background Z from all intensity Z measurements if cells [t] is None: print("Nocellsfound" + str(t)) bothCells = ShapeRoi(cells[t][0]).or(ShapeRoi(cells[t][1])) backRoi = ShapeRoi(Rectangle(0,0,imp.getWidth(),imp.getHeight())).not( bothCells ) ip.setRoi(backRoi) backMean = ip.getStatistics().mean ip.setRoi( cells[t][0] ) stats0 = ip.getStatistics() cellValues0[t] = stats0.mean - backMean cellAreas0[t] = stats0.area * cal.pixelWidth * cal.pixelHeight nuc0 = None for nuc in nuclei[t]: rect = nuc.getBounds() nx = int(rect.x+(rect.width/2.0)) ny = int(rect.y+(rect.height/2.0)) if cells[t][0].contains(nx,ny): nuc0 = nuc break if nuc0 is not None: ip.setRoi( nuc0 ) nucStats0 = ip.getStatistics() nucleusValues0[t] = nucStats0.mean - backMean nucleusAreas0[t] = nucStats0.area * cal.pixelWidth * cal.pixelHeight nuc0.setPosition(0,0,t) nuc0.setStrokeColor(Color.CYAN) ol.add(nuc0) nonnucRoi0 = ShapeRoi(cells[t][0]).not( ShapeRoi(nuc0) ) ip.setRoi( nonnucRoi0 ) nonNucleusValues0[t] = ip.getStatistics().mean - backMean ip.setRoi( cells[t][1] ) stats1 = ip.getStatistics() cellValues1[t] = stats1.mean - backMean cellAreas1[t] = stats1.area * cal.pixelWidth * cal.pixelHeight nuc1 = None for nuc in nuclei[t]: rect = nuc.getBounds() nx = int(rect.x+(rect.width/2.0)) ny = int(rect.y+(rect.height/2.0)) if cells[t][1].contains(nx,ny): nuc1 = nuc break if nuc1 is not None: ip.setRoi( nuc1 ) nucStats1 = ip.getStatistics() nucleusValues1[t] = nucStats1.mean - backMean nucleusAreas1[t] = nucStats1.area * cal.pixelWidth * cal.pixelHeight nuc1.setPosition(0,0,t) nuc1.setStrokeColor(Color.CYAN) ol.add(nuc1) nonnucRoi1 = ShapeRoi(cells[t][1]).not( ShapeRoi(nuc1) ) ip.setRoi( nonnucRoi1 ) nonNucleusValues1[t] = ip.getStatistics().mean - backMean rt = ResultsTable() rt.showRowNumbers(False) for t in range(1,T+1): rt.setValue("Time ("+cal.getTimeUnit()+")", t-1, IJ.d2s(time[t],1)) areaRatio = cellAreas0[t] / cellAreas1[t] if cellAreas0[t]>0 and cellAreas1[t]>0 else 0.0 rt.setValue("Cell 0:Cell 1 Area Ratio", t-1, areaRatio) nucleusRatio = nucleusValues0[t] / nucleusValues1[t] if nucleusValues0[t]>0 and nucleusValues1[t]>0 else 0.0 rt.setValue("Cell 0:Cell 1 Nucleus Ratio", t-1, nucleusRatio) nonNucleusRatio = nonNucleusValues0[t] / nonNucleusValues1[t] if nonNucleusValues0[t]>0 and nonNucleusValues1[t]>0 else 0.0 rt.setValue("Cell 0:Cell 1 Non-Nucleus Ratio", t-1, nonNucleusRatio) nnnRatio0 = nucleusValues0[t] / nonNucleusValues0[t] if nucleusValues0[t]>0 and nonNucleusValues0[t]>0 else 0.0 rt.setValue("Cell 0 Nucleus:Non-Nucleus Ratio", t-1, nnnRatio0) nnnRatio1 = nucleusValues1[t] / nonNucleusValues1[t] if nucleusValues1[t]>0 and nonNucleusValues1[t]>0 else 0.0 rt.setValue("Cell 1 Nucleus:Non-Nucleus Ratio", t-1, nnnRatio1) rt.setValue("Cell 0 (red) Area ("+cal.getUnit()+u"\u00b2"+")", t-1, cellAreas0[t]) rt.setValue("Cell 0 Nucleus Area ("+cal.getUnit()+u"\u00b2"+")", t-1, nucleusAreas0[t]) rt.setValue("Cell 0 All", t-1, cellValues0[t]) rt.setValue("Cell 0 Nucleus", t-1, nucleusValues0[t]) rt.setValue("Cell 0 Non-Nucleus", t-1, nonNucleusValues0[t]) rt.setValue("Cell 1 (green) Area ("+cal.getUnit()+u"\u00b2"+")", t-1, cellAreas1[t]) rt.setValue("Cell 1 Nucleus Area ("+cal.getUnit()+u"\u00b2"+")", t-1, nucleusAreas1[t]) rt.setValue("Cell 1 All", t-1, cellValues1[t]) rt.setValue("Cell 1 Nucleus", t-1, nucleusValues1[t]) rt.setValue("Cell 1 Non-Nucleus", t-1, nonNucleusValues1[t]) rt.show(imp.getTitle()+"-Results") dataset = DefaultXYDataset() dataset.addSeries( "Cell 0", [time[1:], cellValues0[1:]] ) dataset.addSeries( "Cell 1", [time[1:], cellValues1[1:]] ) dataset.addSeries( "Nucleus 0", [time[1:], nucleusValues0[1:]] ) dataset.addSeries( "Nucleus 1", [time[1:], nucleusValues1[1:]] ) dataset.addSeries( "Non-Nucleus 0", [time[1:], nonNucleusValues0[1:]] ) dataset.addSeries( "Non-Nucleus 1", [time[1:], nonNucleusValues1[1:]] ) chart = ChartFactory.createScatterPlot( imp.getTitle(), "Time ("+cal.getTimeUnit()+")", "Intensity Z", dataset, PlotOrientation.VERTICAL, True,True,False ) plot = chart.getPlot() plot.setBackgroundPaint(Color(64, 128, 255)) plot.setDomainGridlinePaint(Color.BLACK) plot.setRangeGridlinePaint(Color.BLACK) renderer = plot.getRenderer() legend = LegendItemCollection() shapeR = 2.0 nucShape = Ellipse2D.Float(-shapeR,-shapeR,shapeR*2,shapeR*2) nonNucShape = Path2D.Float() nonNucShape.moveTo(-shapeR,-shapeR) nonNucShape.lineTo(shapeR,shapeR) nonNucShape.moveTo(shapeR,-shapeR) nonNucShape.lineTo(-shapeR,shapeR) for s in range(dataset.getSeriesCount()): if s == 0: renderer.setSeriesLinesVisible(s, True) renderer.setSeriesShapesVisible(s, False) renderer.setSeriesStroke(s, BasicStroke(1)) renderer.setSeriesPaint(s, Color.RED) legend.add( LegendItem("Cell 0", Color.RED) ) elif s == 1: renderer.setSeriesLinesVisible(s, True) renderer.setSeriesShapesVisible(s, False) renderer.setSeriesStroke(s, BasicStroke(1)) renderer.setSeriesPaint(s, Color.GREEN) legend.add( LegendItem("Cell 1", Color.GREEN) ) elif s == 2: renderer.setSeriesLinesVisible(s, False) renderer.setSeriesShapesVisible(s, True) renderer.setSeriesShape(s, nucShape) renderer.setSeriesPaint(s, Color.RED) elif s == 3: renderer.setSeriesLinesVisible(s, False) renderer.setSeriesShapesVisible(s, True) renderer.setSeriesShape(s, nucShape) renderer.setSeriesPaint(s, Color.GREEN) elif s == 4: renderer.setSeriesLinesVisible(s, False) renderer.setSeriesShapesVisible(s, True) renderer.setSeriesShape(s, nonNucShape) renderer.setSeriesPaint(s, Color.RED) elif s == 5: renderer.setSeriesLinesVisible(s, False) renderer.setSeriesShapesVisible(s, True) renderer.setSeriesShape(s, nonNucShape) renderer.setSeriesPaint(s, Color.GREEN) plot.setFixedLegendItems(legend) frame = ChartFrame(imp.getTitle()+" Z-Normalised Intensity", chart) frame.pack() frame.setSize( Dimension(800, 800) ) frame.setLocationRelativeTo(None) frame.setVisible(True)
def NND(imp, mapC, compareC): cal = imp.getCalibration() title = imp.getTitle() impZ = imp.getNSlices() dup = Duplicator() compare = dup.run(imp, compareC, compareC, 1, impZ, 1, 1) compare = reslice(compare, cal.pixelWidth) IJ.run(compare, "Gaussian Blur 3D...", "x=3 y=3 z=3") Z = compare.getNSlices() IJ.setAutoThreshold(compare, THRESHOLD + " dark stack") Prefs.blackBackground = True IJ.run(compare, "Convert to Mask", "method=" + THRESHOLD + " background=Dark black") IJ.run(compare, "Exact Signed Euclidean Distance Transform (3D)", "") edtcompare = WindowManager.getImage("EDT") edtcompare.getWindow().setVisible(False) mapp = dup.run(imp, mapC, mapC, 1, impZ, 1, 1) mapp = reslice(mapp, cal.pixelWidth) IJ.run(mapp, "Gaussian Blur 3D...", "x=3 y=3 z=3") IJ.setAutoThreshold(mapp, THRESHOLD + " dark stack") Prefs.blackBackground = True IJ.run(mapp, "Convert to Mask", "method=" + THRESHOLD + " background=Dark black") dists = [] rt = ResultsTable() ol = Overlay() row = 0 for z in range(Z): mapp.setPosition(z + 1) IJ.run(mapp, "Create Selection", "") if mapp.getStatistics().mean == 0: IJ.run(mapp, "Make Inverse", "") roi = mapp.getRoi() if roi is None: continue edtcompare.setPosition(z + 1) edtcompare.setRoi(roi) IJ.setBackgroundColor(0, 0, 0) IJ.run(edtcompare, "Clear Outside", "slice") ip = edtcompare.getProcessor() roiList = ShapeRoi(roi).getRois() #split roi to limit bounds for sr in roiList: bounds = sr.getBounds() for y in range(0, bounds.height): for x in range(0, bounds.width): if sr.contains(bounds.x + x, bounds.y + y): d = ip.getf(bounds.x + x, bounds.y + y) * cal.pixelWidth * 1000 rt.setValue("C" + str(mapC) + " X", row, (bounds.x + x) * cal.pixelWidth) rt.setValue("C" + str(mapC) + " Y", row, (bounds.y + y) * cal.pixelHeight) rt.setValue("C" + str(mapC) + " Z", row, z * cal.pixelDepth) rt.setValue("Distance to C" + str(compareC) + " (nm)", row, d) row += 1 histD = d if histD >= 0: #set all overlapping voxel distances to 0 histD = 0 dists.append( -histD) #invert to positive for outside distance posZ = int(((z + 1) / float(Z)) * impZ) + 1 roi.setPosition(0, posZ, 1) roi.setStrokeColor(Colour.MAGENTA) ol.add(roi) compare.setPosition(z + 1) IJ.run(compare, "Create Selection", "") if compare.getStatistics().mean == 0: IJ.run(compare, "Make Inverse", "") compareRoi = compare.getRoi() if compareRoi is not None: compareRoi.setPosition(0, posZ, 1) compareRoi.setStrokeColor(Colour.CYAN) ol.add(compareRoi) edtcompare.killRoi() histogram(title + " C" + str(mapC) + "-C" + str(compareC) + " Distance", dists) rt.show(title + " C" + str(mapC) + "-C" + str(compareC) + " Distance") imp.setOverlay(ol) compare.close() edtcompare.changes = False edtcompare.close() mapp.close()
cell = cell + 1 # save this results table rt.save(directory + "/" + filename + "_GFP.csv") print("saving at ", directory + "/" + filename + "_GFP.csv") # create summary resulta table, with "cell" and "foci_count" columns consol = ResultsTable() consol.incrementCounter() consol.addValue("cell", 0) consol.addValue("foci_count", 0) rowcount = 1 # loop over all cells, add cell number to the "cell" column for count in range(cell): consol.setValue("cell", count, count) # loop over all foci for count in range(rt.size()): # get in which cell that foci is and increase the # counter on the summary results table currcell = int(rt.getValue("cell", count)) consol.setValue( "foci_count", currcell, int(consol.getValue("foci_count", currcell)) + 1) for count in range(1, cell): foci = consol.getValue("foci_count", count) if foci <= 3: cellsperfoci[foci] = cellsperfoci[foci] + 1 else:
for value in test.labelDict[key]: listOfNames[value] = names[key] if imageOrTable == "Results table": rt = ResultsTable.getResultsTable(resultsName) else: measureImp = WM.getImage(imageName) src2 = clij2.push(measureImp) rt = ResultsTable() clij2.statisticsOfBackgroundAndLabelledPixels(src2, test.src, rt) src2.close() resultsName = "Results table" collumnNumber = rt.getLastColumn() + 1 for i in range(len(listOfNames)): try: j = rt.getValue("Identifier", i) except: try: j = rt.getValue("Label", i) except: j = i rt.setValue("Label name", i, listOfNames[int(j)]) rt.setValue("Label value", i, test.labelValues[int(j)]) rt.show(resultsName + " with labels") clij2.clear() labelColorBarImp.close()
def main(): rt = RT.open2(table_file.getAbsolutePath()) if not rt: return log(" --- --- --- ") log("Loaded %s" % table_file.getAbsolutePath()) log("Loading column lists...") # Get column indices from imported file headings = getColumnHeadings(rt) id_col = getColumnIndex(headings, "TID") t_col = getColumnIndex(headings, "t [") d2p_col = getColumnIndex(headings, "D2P [") angle_col = getColumnIndex(headings, u'\u03B1 [deg]') delta_col = getColumnIndex(headings, u'\u0394\u03B1 [deg]') if angle_col == RT.COLUMN_NOT_FOUND: log("Failed to detect index for angle column. Re-trying...") angle_col = getColumnIndex(headings, u'? [deg]') if delta_col == RT.COLUMN_NOT_FOUND: log("Failed to detect index for delta angle column. Re-trying...") delta_col = getColumnIndex(headings, u'?? [deg]') log("Last column index is %s" % rt.getLastColumn()) if RT.COLUMN_NOT_FOUND in (id_col, d2p_col, delta_col, angle_col): uiservice.showDialog("Error: Some key columns were not found!", "Invalid Table?") return log("Settings: BOUT_WINDOW= %s, MIN_D2P= %s, DEF_FRAME_INTERVAL= %s" % (BOUT_WINDOW, '{0:.4f}'.format(MIN_D2P), DEF_FRAME_INTERVAL)) # Store all data on dedicated lists track_id_rows = rt.getColumnAsDoubles(id_col) d2p_rows = rt.getColumnAsDoubles(d2p_col) angle_rows = rt.getColumnAsDoubles(angle_col) delta_rows = rt.getColumnAsDoubles(delta_col) t_rows = rt.getColumnAsDoubles(t_col) # Assess n of data points and extract unique path ids n_rows = len(track_id_rows) row_indices = range(n_rows) track_ids = set(track_id_rows) n_tracks = len(track_ids) log("Table has %g rows" % n_rows) log("Table has %g tracks" % n_tracks) log("Parsing tracks...") for track_id in track_ids: for row, next_row in zip(row_indices, row_indices[1:]): if track_id_rows[row] != track_id: continue if not isNumber(angle_rows[row]): rt.setValue("FLAG", row, "NA") continue lower_bound = max(0, row - BOUT_WINDOW + 1) upper_bound = min(n_rows - 1, row + BOUT_WINDOW) win_d2p = [] for _ in range(lower_bound, upper_bound): win_d2p.append(d2p_rows[row]) if sum(win_d2p) <= MIN_D2P * len(win_d2p): rt.setValue("FLAG", row, 0) else: current_angle = angle_rows[row] next_angle = angle_rows[next_row] current_delta = delta_rows[row] flag = -1 if current_angle < 0 else 1 delta_change = (abs(current_delta) > 90) same_sign = ((current_angle < 0) == (next_angle < 0)) if delta_change and not same_sign: flag *= -1 rt.setValue("FLAG", row, flag) if next_row == n_rows - 1: rt.setValue("FLAG", next_row, flag) if rt.save(table_file.getAbsolutePath()): log("Processed table successfully saved (file overwritten)") else: log("Could not override input file. Displaying it...") rt.show(table_file.name) log("Creating onset table...") onset_rt = RT() onset_rt.showRowNumbers(False) frame_int = DEF_FRAME_INTERVAL if "table" in frame_rate_detection: frame_int = getFrameIntervalFromTable(row_indices, track_id_rows, t_rows) elif "image" in frame_rate_detection: frame_int = getFrameIntervalFromImage(image_file.getAbsolutePath()) else: log("Using default frame rate") for track_id in track_ids: for prev_row, row in zip(row_indices, row_indices[1:]): if not track_id in (track_id_rows[prev_row], track_id_rows[row]): continue flag = rt.getValue("FLAG", row) if not isNumber(flag): continue flag = int(flag) if flag == 0: continue if flag == 1 or flag == -1: srow = onset_rt.getCounter() onset_rt.incrementCounter() onset_rt.setValue("TID", srow, track_id) from_frame = int(t_rows[prev_row] / frame_int) + 1 to_frame = int(t_rows[row] / frame_int) + 1 onset_rt.setValue("First disp. [t]", srow, "%s to %s" % (t_rows[prev_row], t_rows[row])) onset_rt.setValue("First disp. [frames]", srow, "%s to %s" % (from_frame, to_frame)) onset_rt.setValue("ManualTag", srow, "") break out_path = suffixed_path(table_file.getAbsolutePath(), "ManualTagging") if onset_rt.save(out_path): log("Summary table successfully saved: %s" % out_path) else: log("File not saved... Displaying onset table") onset_rt.show("Onsets %s" % table_file.name)
maskStk = imgMask.getStack() im410Stk = img410.getStack() im470Stk = img470.getStack() areas = [] angles = [] xs = [] ys = [] # TODO: subtract median here? ra = roiManager.getRoisAsArray() for i in range(maskStk.getSize()): ip = im410Stk.getProcessor(i+1) ip.setRoi(ra[i]) istats = ip.getStatistics() dataTable.setValue('Intensity410_wholePharynx', i, istats.mean) ip = im470Stk.getProcessor(i+1) ip.setRoi(ra[i]) istats = ip.getStatistics() dataTable.setValue('Intensity470_wholePharynx', i, istats.mean) # TODO: Figure out units for Area dataTable.setValue('Area (Px)', i, istats.area) # we don't need to keep track of these in our `data` object, just need them to do the rotations angles.append(istats.angle) xs.append(istats.xCenterOfMass) ys.append(istats.yCenterOfMass) roiManager.runCommand("reset")
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 rt.show(resultsName+ " with labels") clij2.clear() labelColorBarImp.close() imp1Stats=imp1.getStatistics() print imp1Stats.max tracked=[11]*int(65535) for i,v in enumerate(test.labelValues): if value not in test.errors: tracked[i]= v else:
def writeToTable(mu1, sig1, prior1, mu2, sig2, prior2, threshold): rt = RT(2) rt.setValue("class", 0, 1) rt.setValue("mean", 0, mu1) rt.setValue("stddev", 0, sig1) rt.setValue("prior", 0, prior1) rt.setValue("intersection", 0, threshold) rt.setValue("count", 0, 0) rt.setValue("class", 1, 2) rt.setValue("mean", 1, mu2) rt.setValue("stddev", 1, sig2) rt.setValue("prior", 1, prior2) rt.setValue("intersection", 1, threshold) rt.setValue("count", 1, 0) rt.show("clusters")
class Morph(object): """ Fourni les mesures principales pour l'analyse des cellules bacteriennes: proprietes: 1-MaxFeret 2-MinFeret 3-AngleFeret 4-XFeret 5-YFeret 6-Area 7-Mean 8-StdDev 9-IntDen 10-Kurt 11-Skew 12-Angle 13-Major 14-Minor 15-Solidity 16-AR 17-Round 18-Circ. 19-XM 20-YM 21-X 22-Y 23-FerCoord: tuple contenant x1, y1, x2, y2 du MaxFeret 24-Fprofil: list contenant les valeurs du profil le long de MaxFeret 25-FerAxis: Line ROI 26-MidAxis: Polyline ROI de l'axe median par skeletonize 27-MidProfil: list contenant les valeurs du profil le long de MidAxis 28-nb Foci 29-ListFoci: liste des positions des foci par cellule 30-ListAreaFoci: liste des area des foci 31-ListPeaksFoci: liste des int max des foci 32-ListMeanFoci liste des int mean des foci toute les proprietes mettent a jour l'image cible par: object.propriete=imp Methodes: getFeretSegments(n segments) getMidSegments(n segments, radius, tool 0= ligne perpendiculaire, 1= cercle, 2= ligne tangente) selectInitRoi: active la ROI initiale Statics: distMorph(liste de coordonees a mesurer= (coefficient, valeur initiale, valeur finale)) setteurs: setImage(ImagePlus) setImageMeasures(imagePlus) met a jours les mesures avec imagePlus setImageMidprofil(imagePlus) met a jours le profil avec imagePlus setLineWidth(width) afecte la largeur de ligne pour le profil pour Fprofile et MidProfil defaut = 0 setshowFprof(True) affiche le graphique de profil Fprofil defaut = False setMidParams(longueur mesurer l'angle de l'extremite en pixels defaut=10, coefficient pour prolonger et trouver l'intersection avec le contour defaut=1.3 """ def __Measures(self): self.__boolmeasures=True if (self.__contour is not None) and (self.__contour.getType() not in [9,10]): self.__image.killRoi() self.__image.setRoi(self.__contour) self.__ip=self.__image.getProcessor() self.__rt= ResultsTable() analyser= Analyzer(self.__image, Analyzer.AREA+Analyzer.CENTER_OF_MASS+Analyzer.CENTROID+Analyzer.ELLIPSE+Analyzer.FERET+Analyzer.INTEGRATED_DENSITY+Analyzer.MEAN+Analyzer.KURTOSIS+Analyzer.SKEWNESS+Analyzer.MEDIAN+Analyzer.MIN_MAX+Analyzer.MODE+Analyzer.RECT+Analyzer.SHAPE_DESCRIPTORS+Analyzer.SLICE+Analyzer.STACK_POSITION+Analyzer.STD_DEV, self.__rt) analyser.measure() #self.__rt.show("myRT") else: self.__rt = ResultsTable() analyser = Analyzer(self.__image, Analyzer.AREA+Analyzer.CENTER_OF_MASS+Analyzer.CENTROID+Analyzer.ELLIPSE+Analyzer.FERET+Analyzer.INTEGRATED_DENSITY+Analyzer.MEAN+Analyzer.KURTOSIS+Analyzer.SKEWNESS+Analyzer.MEDIAN+Analyzer.MIN_MAX+Analyzer.MODE+Analyzer.RECT+Analyzer.SHAPE_DESCRIPTORS+Analyzer.SLICE+Analyzer.STACK_POSITION+Analyzer.STD_DEV, self.__rt) analyser.measure() #self.__rt.show("myRT") maxValues=self.__rt.getRowAsString(0).split("\t") heads=self.__rt.getColumnHeadings().split("\t") for val in heads: self.__rt.setValue(val, 0, Float.NaN) #self.__rt.show("myRT") # calculate the 1/2 , 1/4 ... 1/n positions for a liste while 1/n >= 1 returns a dict = 0: (0, [0, 0, pos(1/2)]) 1: (1, [-1, -0.5, -pos(1/4)], [0, 0, pos(1/2)], [1, 0.5, pos(1/2)]) def __Centers(self, line) : L=len(line) l2=L//2 l=L pos={} for i in range(self.log2(L)) : l = l//2 pos[i]=l l=L dicPos={} jtot=1 for i in range(self.log2(L)) : s=[] j=1 while (l2-j*pos[i])>0 or (l2+j*pos[i])<L : s.append((-j,(l2-j*pos[i]))) s.append((j,(l2+j*pos[i]))) j=j+1 s.append((0,l2)) s.sort() if ((len(s)+1)*pos[i]-L)//pos[i] > 0 : del s[0] del s[-1] else : pass if len(s) - 1 != 0 : jtot= (( len(s) - 1 ) / 2.00)+1 else : jtot=1 centers=[[v[0], v[0]/jtot, v[1]] for v in s] dicPos[i]=(i, centers) del(s) return dicPos #calculate angle from the center of the midline to ends def __flexAngle(self) : try : p1 = self.__midLine[0] p3 = self.__midLine[-1] except AttributeError : self.__midline() p1 = self.__midLine[0] p3 = self.__midLine[-1] icenter = self.__midCenters[0][1][0][2] p2 = self.__midLine[icenter] #xpoints = (429,472,466) #ypoints = (114,133,99) xpoints = [int(p1[0]), int(p2[0]), int(p3[0])] ypoints = [int(p1[1]), int(p2[1]), int(p3[1])] #print ypoints #return "" r = PolygonRoi(xpoints, ypoints, 3, Roi.ANGLE) return r.getAngle() def __NbFoci(self): self.__boolFoci=True self.__image.killRoi() self.__image.setRoi(self.__contour) self.__ip=self.__image.getProcessor() rt=ResultsTable.getResultsTable() rt.reset() mf=MaximumFinder() mf.findMaxima(self.__ip, self.__noise, 0, MaximumFinder.LIST, True, False) self.__listMax[:]=[] #feret=self.getFercoord() #xc=feret[0]-((feret[0]-feret[2])/2.0) #yc=feret[1]-((feret[1]-feret[3])/2.0) #print xc, yc xc=self.getXC() yc=self.getYC() #print xc, yc for i in range(rt.getCounter()): x=int(rt.getValue("X", i)) y=int(rt.getValue("Y", i)) size=self.__localwand(x, y, self.__ip, self.__seuilPeaks, self.__peaksMethod, self.__light) coord=[(1, xc, x), (1, yc, y)] d=self.distMorph(coord,"Euclidean distance") d=( d / (self.getMaxF()/2) )*100 self.__listMax.append((x, y, size[0], size[1], size[2], size[3], size[4], d)) rt.reset() def __FeretAxis(self): __boolFL=True if (self.__contour is not None) and (self.__contour.getType() in range(1,11)): self.__image.killRoi() self.__image.setRoi(self.__contour) if self.__contour.getType() in [1,5,9,10]: self.__polygon=self.__contour.getPolygon() else: self.__polygon=self.__contour.getFloatPolygon() points = self.__polygon.npoints self.__polx = self.__polygon.xpoints self.__poly = self.__polygon.ypoints diameter=0.0 for i in range(points): for j in range(i, points): dx=self.__polx[i]-self.__polx[j] dy=self.__poly[i]-self.__poly[j] d=math.sqrt(dx*dx+dy*dy) if d>diameter: diameter=d i1=i i2=j tempDictY={ self.__poly[i1]:(self.__polx[i1],self.__poly[i1],self.__polx[i2],self.__poly[i2]), self.__poly[i2]:(self.__polx[i2],self.__poly[i2],self.__polx[i1],self.__poly[i1]) } minY=min((self.__poly[i1],self.__poly[i2])) maxY=max((self.__poly[i1],self.__poly[i2])) lineTuple=tempDictY[maxY] self.__x1=lineTuple[0] self.__y1=lineTuple[1] self.__x2=lineTuple[2] self.__y2=lineTuple[3] self.__line= Line(self.__x1,self.__y1,self.__x2,self.__y2) elif (self.__contour is not None) and (self.__contour.getType()==0): self.__x2=self.__contour.getBounds().x self.__y2=self.__contour.getBounds().y self.__x1=self.__contour.getBounds().x+self.__contour.getBounds().width self.__y1=self.__contour.getBounds().y+self.__contour.getBounds().height self.__line= Line(self.__x1,self.__y1,self.__x2,self.__y2) else: self.__x1="NaN" self.__y1="NaN" self.__x2="NaN" self.__y2="NaN" self.__fprofArray="NaN" def __FeretProfile(self): """ genere le profile le long du diametre de Feret """ self.__line.setWidth(self.__lw) self.__image.setRoi(self.__line, True) self.__fprof= ProfilePlot(self.__image) self.__fprofArray=self.__fprof.getProfile() if self.__showFpro: self.__fprof.createWindow() self.__image.killRoi() self.__line.setWidth(0) self.__image.setRoi(self.__contour) return self.__fprofArray def __midline(self): debug=False #print "line 251", self.__boolML if self.__boolML : ordpoints=self.__midLine[:] npoints=len(ordpoints) xpoints=[point[0] for point in ordpoints] ypoints=[point[1] for point in ordpoints] polyOrd=PolygonRoi(xpoints, ypoints, npoints, PolygonRoi.POLYLINE) return polyOrd #if self.getMaxF()<15 : return None #self.__FeretAxis() #return self.__line self.__boolML=True self.__image.killRoi() self.__image.setRoi(self.__contour) boundRect=self.__contour.getBounds() boundRoi=Roi(boundRect) xori=boundRect.x yori=boundRect.y wori=boundRect.width hori=boundRect.height ip2 = ByteProcessor(self.__image.getWidth(), self.__image.getHeight()) ip2.setColor(255) ip2.setRoi(self.__contour) ip2.fill(self.__contour) skmp=ImagePlus("ip2", ip2) skmp.setRoi(xori-1,yori-1,wori+1,hori+1) ip3=ip2.crop() skmp3=ImagePlus("ip3", ip3) skmp3.killRoi() #------------------------------------------------------------- if debug : skmp3.show() IJ.showMessage("imp3 l287") #------------------------------------------------------------- IJ.run(skmp3, "Skeletonize (2D/3D)", "") #IJ.run(skmp3, "Skeletonize", "") #------------------------------------------------------------- if debug : skmp3.show() IJ.showMessage("imp3 l294") #------------------------------------------------------------- IJ.run(skmp3, "BinaryConnectivity ", "white") ip3.setThreshold(3,4, ImageProcessor.BLACK_AND_WHITE_LUT) IJ.run(skmp3, "Convert to Mask", "") #------------------------------------------------------------- if debug : skmp3.show() IJ.showMessage("imp3 l302") #------------------------------------------------------------- #IJ.run(skmp3, "Skeletonize", "") #------------------------------------------------------------- if debug : skmp3.updateAndDraw() skmp3.show() IJ.showMessage("imp3 l308") #------------------------------------------------------------- rawPoints=[] w=ip3.getWidth() h=ip3.getHeight() rawPoints=[(x+xori,y+yori,self.__sommeVals(x,y,ip3)) for x in range(w) for y in range(h) if ip3.getPixel(x,y)==255] tempbouts=[val for val in rawPoints if val[2]==2] if len(tempbouts)!=2 : return None # test #if len(tempbouts)!=2 : # # IJ.run(skmp3, "BinaryConnectivity ", "white") # ip3.setThreshold(3,3, ImageProcessor.BLACK_AND_WHITE_LUT) # IJ.run(skmp3, "Convert to Mask", "") # #------------------------------------------------------------- # if debug==debug : # skmp3.updateAndDraw() # skmp3.show() # IJ.showMessage("if test l 328") ##------------------------------------------------------------- # rawPoints=[(x+xori,y+yori,self.__sommeVals(x,y,ip3)) for x in range(w) for y in range(h) if ip3.getPixel(x,y)==255] # tempbouts=[val for val in rawPoints if val[2]==2] ip3.setRoi(boundRect) if rawPoints==[]: return None npoints=len(rawPoints) xpoints=[point[0] for point in rawPoints] ypoints=[point[1] for point in rawPoints] valpoints=[point[2] for point in rawPoints] bouts={} if tempbouts==[]: return None if tempbouts[0][1]>tempbouts[1][1]: bouts["A"]=tempbouts[0] bouts["B"]=tempbouts[1] else: bouts["A"]=tempbouts[1] bouts["B"]=tempbouts[0] rawPoints.remove(bouts["A"]) rawPoints.remove(bouts["B"]) rawPoints.append(bouts["B"]) tempList=[val for val in rawPoints] p=bouts["A"] Dist={} ordPoints=[] for j in range(len(rawPoints)): Dist.clear() for i in range(len(tempList)): dx=p[0]-tempList[i][0] dy=p[1]-tempList[i][1] d=math.sqrt(dx*dx+dy*dy) Dist[d]=tempList[i] distList=Dist.keys() mind=min(distList) nextpoint=Dist[mind] ordPoints.append(nextpoint) tempList.remove(nextpoint) p=nextpoint ordPoints.insert(0, bouts["A"]) npoints=len(ordPoints) if npoints < 4 : return None xpoints=[point[0] for point in ordPoints] ypoints=[point[1] for point in ordPoints] polyOrd1=PolygonRoi(xpoints, ypoints, npoints, PolygonRoi.POLYLINE) f=min(self.__midParams[0], len(xpoints)//2) angleA1=polyOrd1.getAngle(xpoints[0],ypoints[0], xpoints[1],ypoints[1]) angleA2=polyOrd1.getAngle(xpoints[1],ypoints[1], xpoints[2],ypoints[3]) angleA = (angleA1+angleA2)/2.00 angleA=polyOrd1.getAngle(xpoints[0],ypoints[0], xpoints[f],ypoints[f]) angleA=angleA*(math.pi/180) angleB1=polyOrd1.getAngle(xpoints[-2],ypoints[-2], xpoints[-1],ypoints[-1]) angleB2=polyOrd1.getAngle(xpoints[-3],ypoints[-3], xpoints[-2],ypoints[-2]) angleB = (angleB1+angleB2)/2.00 angleB=polyOrd1.getAngle(xpoints[-f],ypoints[-f], xpoints[-1],ypoints[-1]) angleB=angleB*(math.pi/180) coef=self.__midParams[1] xa = xpoints[0]-coef*f*math.cos(angleA) ya = ypoints[0]+coef*f*math.sin(angleA) xb = xpoints[-1]+coef*f*math.cos(angleB) yb = ypoints[-1]-coef*f*math.sin(angleB) lineA=Line(xpoints[0],ypoints[0], xa, ya) lineB=Line(xpoints[-1],ypoints[-1], xb, yb) lineA.setWidth(0) lineB.setWidth(0) lineA.setStrokeWidth(0) lineB.setStrokeWidth(0) ip2.setColor(0) ip2.fill() ip2.setColor(255) ip2.setRoi(lineA) lineA.drawPixels(ip2) ip2.setRoi(lineB) lineB.drawPixels(ip2) ip2.setRoi(self.__contour) ip2.setColor(0) ip2.fillOutside(self.__contour) ip2=ip2.crop() imb=ImagePlus("new-ip2", ip2) #------------------------------------------------------------- if debug : imb.show() IJ.showMessage("imb l416") #------------------------------------------------------------- w2=ip2.getWidth() h2=ip2.getHeight() ip4 = ByteProcessor(w2+2, h2+2) im4=ImagePlus("im4", ip4) for i in range(w2): for j in range(h2): ip4.set(i+1,j+1,max([ip2.getPixel(i,j),ip3.getPixel(i,j)])) #im4.show() #------------------------------------------------------------- if debug : im4.show() IJ.showMessage("im4 l430") #------------------------------------------------------------- im4.killRoi() #IJ.run(im4, "Skeletonize (2D/3D)", "") #IJ.run(skmp3, "Skeletonize", "") #------------------------------------------------------------- if debug : imb.show() IJ.showMessage("imb l300") #------------------------------------------------------------- #IJ.run(skmp3, "Skeletonize", "") ip4=im4.getProcessor() rawPoints2=[] w4=ip4.getWidth() h4=ip4.getHeight() rawPoints2=[(x+xori-2,y+yori-2,self.__sommeVals(x,y,ip4)) for x in range(w4) for y in range(h4) if ip4.getPixel(x,y)==255] self.__MidBouts=[val for val in rawPoints2 if val[2]==2] # test if len(self.__MidBouts)!=2 : IJ.run(im4, "BinaryConnectivity ", "white") ip4.setThreshold(3,3, ImageProcessor.BLACK_AND_WHITE_LUT) IJ.run(im4, "Convert to Mask", "") rawPoints2=[(x+xori-2,y+yori-2,self.__sommeVals(x,y,ip4)) for x in range(w4) for y in range(h4) if ip4.getPixel(x,y)==255] self.__MidBouts=[val for val in rawPoints2 if val[2]==2] ordpoints=[] p0=self.__MidBouts[0] rawPoints2.remove(p0) c=0 while p0!=self.__MidBouts[1]: if c<len(rawPoints2): point=rawPoints2[c] else: break if abs(point[0]-p0[0])<2 and abs(point[1]-p0[1])<2: p0=point ordpoints.append(point) rawPoints2.remove(point) c=0 else: c=c+1 ordpoints.insert(0, self.__MidBouts[0]) self.__midLine=ordpoints[:] self.__midCenters = self.__Centers(self.__midLine) npoints=len(ordpoints) xpoints=[point[0] for point in ordpoints] ypoints=[point[1] for point in ordpoints] polyOrd=PolygonRoi(xpoints, ypoints, npoints, PolygonRoi.POLYLINE) #print self.__midLine #print self.__MidBouts #print xpoints #print ypoints return polyOrd def __sommeVals(self, x, y, ip): return (ip.getPixel(x,y)+ip.getPixel(x-1,y-1)+ip.getPixel(x,y-1)+ip.getPixel(x+1,y-1)+ip.getPixel(x-1,y)+ip.getPixel(x+1,y)+ip.getPixel(x-1,y+1)+ip.getPixel(x,y+1)+ip.getPixel(x+1,y+1))/255 def __localwand(self, x, y, ip, seuil, method, light): self.__image.killRoi() ip.snapshot() if method == "mean" : peak=ip.getPixel(x,y) tol = (peak - self.getMean())*seuil w = Wand(ip) w.autoOutline(x, y, tol, Wand.EIGHT_CONNECTED) #print "method=", method, tol, peak elif method == "background" : radius = self.getMinF()/4 bs = BackgroundSubtracter() #rollingBallBackground(ImageProcessor ip, double radius, boolean createBackground, boolean lightBackground, boolean useParaboloid, boolean doPresmooth, boolean correctCorners) bs.rollingBallBackground(ip, radius, False, light, False, True, False) peak=ip.getPixel(x,y) tol = peak*seuil w = Wand(ip) w.autoOutline(x, y, tol, Wand.EIGHT_CONNECTED) ip.reset() #print "method=", method, tol, radius, peak else : peak=ip.getPixel(x,y) tol = peak*seuil w = Wand(ip) w.autoOutline(x, y, tol, Wand.EIGHT_CONNECTED) #print "method=", method, tol peak=ip.getPixel(x,y) temproi=PolygonRoi(w.xpoints, w.ypoints, w.npoints, PolygonRoi.POLYGON) self.__image.setRoi(temproi) #self.__image.show() #time.sleep(1) #peakip=self.__image.getProcessor() #stats=peakip.getStatistics() temprt = ResultsTable() analyser = Analyzer(self.__image, Analyzer.AREA+Analyzer.INTEGRATED_DENSITY+Analyzer.FERET, temprt) analyser.measure() #temprt.show("temprt") rtValues=temprt.getRowAsString(0).split("\t") area=float(rtValues[1]) intDen=float(rtValues[4]) feret=float(rtValues[2]) mean=intDen/area #time.sleep(2) temprt.reset() self.__image.killRoi() return [peak, area, mean, intDen, feret] def __MidProfil(self): if not self.__boolML : self.__midline() ip=self.__image.getProcessor() line=Line(self.__midLine[0][0],self.__midLine[0][1],self.__midLine[-1][0],self.__midLine[-1][1]) line.setWidth(self.__lw) self.__MprofArray=[] self.__MprofArray[:]=[] for i in range(0,len(self.__midLine)-1): templine=Line(self.__midLine[i][0],self.__midLine[i][1],self.__midLine[i+1][0],self.__midLine[i+1][1]) templine.setWidth(self.__lw) self.__image.setRoi(templine) #time.sleep(0.5) temprof= ProfilePlot(self.__image) temparray=temprof.getProfile() self.__MprofArray+=temparray templine.setWidth(0) #if self.__showMidpro: self.__fprof.createWindow() return def getFeretSegments(self, n): self.__boolFS=True if(not self.__boolFL): self.__FeretAxis() radius=self.getMinF() lsegment=self.__line.getLength()/((n-1)*2) xo=self.__x1 yo=self.__y1 xf=self.__x2 yf=self.__y2 angle1=self.getAngF()*(math.pi/180) angle2=self.getAngF()*(math.pi/180)+(math.pi/2) avancex=(lsegment*2)*math.cos(angle1) avancey=(lsegment*2)*math.sin(angle1) delta90x=(radius)*math.cos(angle2) delta90y=(radius)*math.sin(angle2) self.__line.setWidth(int(lsegment*2)) #self.__image.setRoi(self.__line) tempcontour=self.__contour.clone() shapeContour=ShapeRoi(tempcontour) segsRoi=[] for i in range(n): tempLine=Line(xo-delta90x, yo+delta90y, xo+delta90x, yo-delta90y) tempLine.setWidth(int(lsegment*2)) poly=tempLine.getPolygon() roipol=PolygonRoi(poly, Roi.POLYGON) shapePoly= ShapeRoi(roipol) interShape=shapePoly.and(shapeContour) segsRoi.append(interShape.shapeToRoi()) xo=xo+avancex yo=yo-avancey #self.__image.setRoi(self.__contour, True) #time.sleep(0) self.__line.setWidth(0) #self.__image.setRoi(tempcontour) #self.__image.updateAndDraw() return segsRoi # return Roi array def getMidSegments(self, n=10, r=5, tool=0): self.__boolMS=True if(not self.__boolML): self.__midline() lsegment=int(len(self.__midLine)/n) if lsegment<2:lsegment=2 ls2=int(len(self.__midLine)/(2*n)) if ls2<1: ls2=1 ip=self.__image.getProcessor() #print(len(self.__midLine), lsegment, ls2) xo=self.__MidBouts[0][0] yo=self.__MidBouts[0][1] xf=self.__MidBouts[1][0] yf=self.__MidBouts[1][1] line1=Line(xo,yo,xf,yf) line1.setWidth(0) angles=[line1.getAngle(self.__midLine[i][0], self.__midLine[i][1], self.__midLine[i+lsegment][0], self.__midLine[i+lsegment][1]) for i in range(0,len(self.__midLine)-lsegment,lsegment)] points=[self.__midLine[i] for i in range(0,len(self.__midLine),lsegment)] lastangle=line1.getAngle(self.__midLine[-ls2][0],self.__midLine[-ls2][1],self.__midLine[-1][0],self.__midLine[-1][1]) angles.append(lastangle) tempcontour=self.__contour.clone() shapeContour=ShapeRoi(tempcontour) angles=[angle*(math.pi/180)+(math.pi/2) for angle in angles] line1.setWidth((ls2+1)*2) segsRoi=[] linesRois=[] cRois=[] for i in range(len(angles)): x=points[i][0] y=points[i][1] cRois.append(PointRoi(x,y)) if tool==0: # ligne perpendiculaire d'epaiseur (ls2+1)*2 line1.setWidth((ls2+1)*2) x1=x+r*math.cos(angles[i]) y1=y-r*math.sin(angles[i]) x2=x-r*math.cos(angles[i]) y2=y+r*math.sin(angles[i]) #print(x, y, x1, y1, x2, y2) tempLine=Line(x1,y1,x2,y2) linesRois.append(tempLine) tempLine.setWidth((ls2+1)*2) #self.__image.setRoi(tempLine, True) #time.sleep(0.3) poly=tempLine.getPolygon() roipol=PolygonRoi(poly, Roi.POLYGON) shapePoly= ShapeRoi(roipol) elif tool==1: #r1=r*0.7 x1=x+r y1=y-r x2=x-r y2=y+r ellipse=EllipseRoi(x1, y1, x2, y2, 1) linesRois.append(ellipse) #print(x, y, x1, y1, x2, y2) #self.__image.setRoi(ellipse, True) shapePoly= ShapeRoi(ellipse) #time.sleep(0.3) else: x1=x y1=y line1.setWidth(r) if (i+1)<len(points): x2=points[i+1][0] y2=points[i+1][1] else: #x1=x+lsegment*math.cos(angles[i]-(math.pi/2)) #y1=y-lsegment*math.sin(angles[i]-(math.pi/2)) x2=x+lsegment*math.cos(angles[i]-(math.pi/2)) y2=y-lsegment*math.sin(angles[i]-(math.pi/2)) #x2=xf #y2=yf tempLine=Line(x1,y1,x2,y2) linesRois.append(tempLine) tempLine.setWidth(r) #self.__image.setRoi(tempLine, True) #time.sleep(0.5) poly=tempLine.getPolygon() roipol=PolygonRoi(poly, Roi.POLYGON) shapePoly= ShapeRoi(roipol) interShape=shapePoly.and(shapeContour) interRoi=interShape.shapeToRoi() segsRoi.append(interShape.shapeToRoi()) line1.setWidth(0) return (segsRoi, linesRois, cRois) def selectInitRoi(self): self.__image.killRoi() self.__image.setRoi(self.__contour) time.sleep(0) @staticmethod def distMorph(coord,distmethod="Euclidean distance"): if distmethod == "Euclidean distance" : s=[val[0]*(val[2]-val[1])*(val[2]-val[1]) for val in coord] #print s #print sum(s) return math.sqrt(sum(s)) if distmethod == "Logarithm distance" : s=[val[0]*abs(math.log(val[2]/val[1])) for val in coord] return sum(s) @staticmethod def log2(n) : return math.log(n)/math.log(2) def Out(self): print("out") #------ end methodes--------------- #------ constructeur ------------- def __init__(self, imp, roi): self.__lw=0 self.__showFpro=False self.__Feret=[] self.__image=imp self.__cal=imp.getCalibration() self.__contour=roi.clone() self.__boolmeasures=False self.__boolFP=False self.__boolFL=False self.__boolML=False self.__boolMP=False self.__boolFS=False self.__boolMS=False self.__boolFoci=False self.__midParams=[10, 1.3] self.__listMax=[] self.__noise=150 self.__seuilPeaks=0.75 self.__peaksMethod="mean" self.__light=False self.__distot=0.00 self.__flexangle=0.00 #print "dropbox MorphoBactProject" #---------- end constructor--------- #---------- getteurs---------------- def getMaxF(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Feret", 0) def getMinF(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("MinFeret", 0) def getXF(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("FeretX", 0) def getYF(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("FeretY", 0) def getAngF(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("FeretAngle", 0) def getArea(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Area", 0) def getMean(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Mean", 0) def getKurt(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Kurt", 0) def getSkew(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Skew", 0) def getIntDen(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("IntDen", 0) def getStdDev(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("StdDev", 0) def getAngle(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Angle", 0) def getMajor(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Major", 0) def getMinor(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Minor", 0) def getSolidity(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Solidity", 0) def getAR(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("AR", 0) def getRound(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Round", 0) def getCirc(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Circ.", 0) def getXM(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("XM",0) def getYM(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("YM",0) def getXC(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("X",0) def getYC(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Y",0) def getNfoci(self): if(not self.__boolFoci):self.__NbFoci() return len(self.__listMax) def getListFoci(self): if(not self.__boolFoci):self.__NbFoci() xy=[] for val in self.__listMax: xy.append((val[0], val[1])) return xy def getListPeaksFoci(self): if(not self.__boolFoci):self.__NbFoci() peaks=[] for val in self.__listMax: peaks.append(val[2]) return peaks def getListAreaFoci(self): if(not self.__boolFoci):self.__NbFoci() areas=[] for val in self.__listMax: areas.append(val[3]) return areas def getListMeanFoci(self): if(not self.__boolFoci):self.__NbFoci() means=[] for val in self.__listMax: means.append(val[4]) return means def getListIntDenFoci(self): if(not self.__boolFoci):self.__NbFoci() ints=[] for val in self.__listMax: ints.append(val[5]) return ints def getListFeretFoci(self): if(not self.__boolFoci):self.__NbFoci() ferets=[] for val in self.__listMax: ferets.append(val[6]) return ferets def getListDistsFoci(self): if(not self.__boolFoci):self.__NbFoci() dists=[] for val in self.__listMax: dists.append(val[7]) return dists def getFercoord(self): """ FerCoord: tuple contenant x1, y1, x2, y2 du MaxFeret """ if (not self.__boolFL): self.__FeretAxis() return (self.__x1,self.__y1,self.__x2,self.__y2) def getFprofil(self): """ Fprofil: list contenant les valeurs du profil le long de MaxFeret """ if (not self.__boolFL): self.__FeretAxis() self.__FeretProfile() return self.__fprofArray def getFerAxis(self): """ FerAxis: Line ROI """ if(not self.__boolFL): self.__FeretAxis() return self.__line def getMidAxis(self): """ MidAxis: Polyline ROI de l'axe median par skeletonize """ if(not self.__boolML): return self.__midline() def getMidSegs(self, n, r, tool): """ Rois des segments 0 = rois , 1 = points, 2 = lines ou ellipses """ if(not self.__boolMS): return self.getMidSegments(n, r, tool) def getMidProfil(self): """ MidProfil: list contenant les valeurs du profil le long de MidAxis """ self.__MidProfil() return self.__MprofArray def getMidPoints(self) : """ MidPoints : list of two extreme points of mid Axis """ if(not self.__boolML): self.__midline() return self.__MidBouts def getCenters(self) : if(not self.__boolML): self.__midline() return self.__midCenters def getFlexAngle(self) : return self.__flexAngle() #------ setteurs -------- def setImage(self, imp): self.__image=imp def setImageMeasures(self, imp): self.__image=imp self.__Measures() def setImageFprofil(self, imp): self.__image=imp self.__FeretProfile() def setImageMidprofil(self, imp): self.__image=imp self.__MidProfil() def setLineWidth(self, lw): self.__lw=lw def setshowFpro(self, fpshow): self.__showFpro=fpshow def setMidParams(self, lseg, coeff): self.__midParams[:]=[] self.__midParams.append(lseg) self.__midParams.append(coeff) def setNoise(self, noise): self.__noise=noise def setSeuilPeaks(self, seuil): self.__seuilPeaks=seuil def setpeaksMethod(self, method): self.__peaksMethod=method def setlight(self, light): self.__light=light #------- properties ----------------------- MaxFeret=property(getMaxF, setImageMeasures, doc="caliper max Feret=") MinFeret=property(getMinF, setImageMeasures, doc="caliper min Feret=") AngleFeret=property(getAngF, setImageMeasures, doc="angle Feret=") XFeret=property(getXF, setImageMeasures, doc="X Feret=") YFeret=property(getYF, setImageMeasures, doc="Y Feret=") Area=property(getArea, setImageMeasures, doc="Area=") Mean=property(getMean, setImageMeasures, doc="Mean=") Kurt=property(getKurt, setImageMeasures, doc="Kurtosis=") Skew=property(getSkew, setImageMeasures, doc="Skewness=") IntDen=property(getIntDen, setImageMeasures, doc="Integrated Intensity=") StdDev=property(getStdDev, setImageMeasures, doc="Standard Deviation=") Angle=property(getAngle, setImageMeasures, doc="Angle=") Major=property(getMajor, setImageMeasures, doc="Major ellipse axis=") Minor=property(getMinor, setImageMeasures, doc="Minor ellipse axis=") Solidity=property(getSolidity, setImageMeasures, doc="Solidity area/convexHull=") AR=property(getAR, setImageMeasures, doc="Major axis/Minor axis=") Round=property(getRound, setImageMeasures, doc="Area/(pi*Major*Major)=1/AR=") Circ=property(getCirc, setImageMeasures, doc="(4*pi*Area)/(perimeter*perimeter)=") XM=property(getXM, setImageMeasures, doc="X center of Mass=") YM=property(getYM, setImageMeasures, doc="Y center of Mass=") XC=property(getXC, setImageMeasures, doc="X of centroid=") YC=property(getYC, setImageMeasures, doc="Y of centroid=") NFoci=property(getNfoci, setImageMeasures, doc="nb foci in the roi=") ListFoci=property(getListFoci, setImageMeasures, doc="list of foci coordinates=") ListPeaksFoci=property(getListPeaksFoci, setImageMeasures, doc="list of foci peaks=") ListAreaFoci=property(getListAreaFoci, setImageMeasures, doc="list of foci areas=") ListMeanFoci=property(getListMeanFoci, setImageMeasures, doc="list of foci means=") ListIntDenFoci=property(getListIntDenFoci, setImageMeasures, doc="list of foci IntDen=") ListFeretFoci=property(getListFeretFoci, setImageMeasures, doc="list of foci Ferets=") ListDistsFoci=property(getListDistsFoci, setImageMeasures, doc="list of foci distances=") FerCoord=property(getFercoord, doc="x1, y1, x2, y2 of Feret diameter =") Fprofil=property(getFprofil, setImageFprofil, doc="Profil along Feret diameter") # return array values FerAxis=property(getFerAxis, doc="ROI along Feret diameter") # return Roi MidAxis=property(getMidAxis, doc="ROI along the median axis") # return Roi MidProfil=property(getMidProfil, setImageMidprofil, doc="profile values of mid axis") # return array values MidPoints=property(getMidPoints, doc= "extreme points of mid line") Centers=property(getCenters, doc= "list of positions (tuples) of 1/2 of the midaxis, 1/4, 1/8 ...") # return a list of tuples FlexAngle=property(getFlexAngle, doc="angle of the center of midline to ends")
rt = ResultsTable() for i in range(roim.getCount()): roi = roim.getRoi(i) # these ore the points in the roi points = roi.getContainedPoints() # this is an array of True,False if the pixel is on the border border = [ (p.x==0) or(p.x==w-1) or (p.y==0) or (p.y==h-1) for p in points] # this is the length of parts of the roi touching a border length_border = sum(border)*px2um perim = roi.getLength() stats = roi.getStatistics() rt.setValue("Label",i,i+1) rt.setValue("Area", i, stats.area*px2um**2) rt.setValue("Perim",i,perim) rt.setValue("Border Length",i, length_border) rt.setValue("Perim non-border", i, perim-length_border) rt.setValue("Width", i,stats.roiWidth*px2um) rt.setValue("Height", i,stats.roiHeight*px2um) rt.setValue("Major", i,stats.major*px2um) rt.setValue("Minor", i,stats.minor*px2um) rt.show("Corrected perimeter")
def main(tableName, showPlot): image = IJ.getImage(); roi = image.getRoi() if not roi: center = image.getWidth() / 2, image.getHeight() / 2 else: center = roi.getXBase(), roi.getYBase(); table = ResultsTable.getResultsTable(tableName) vectors = getVectorsFromTable(table, center) radialVelocity = calculateRadialVelocityPerTime(vectors, center) radialVelocityAndDistanceByTrack(table, center) stats = Tools.getStatistics(radialVelocity) median = calculateMedian(radialVelocity) rt = ResultsTable.getResultsTable(TABLE_NAME) if not rt: rt = ResultsTable() row = rt.getCounter() rt.setValue("label", row, tableName) rt.setValue("x", row, center[0]) rt.setValue("y", row, center[1]) rt.setValue("mean", row, stats.mean) rt.setValue("stdDev", row, stats.stdDev) rt.setValue("min", row, stats.min) rt.setValue("median", row, median) rt.setValue("max", row, stats.max) rt.show(TABLE_NAME) if showPlot: plot(radialVelocity, center)
dotRoi = OvalRoi(int(yA[i] - xyoffset), int(xA[i] - xyoffset), thdist, thdist) ipch2.setRoi(dotRoi) #stats = IS.getStatistics(ip, options, imp.getCalibration()) stats = IS.getStatistics(ipch2, options, cal) ipch3.setRoi(dotRoi) statsch3 = IS.getStatistics(ipch3, options, cal) print "dot", i print "...ch2 TotalInt ", stats.area * stats.mean print "...ch2 Area ", stats.area print "...ch2 mean ", stats.mean print ".." print "...ch3 TotalInt ", statsch3.area * statsch3.mean print "...ch3 Area ", statsch3.area print "...ch3 mean ", statsch3.mean rt.incrementCounter() rt.setValue("DotID", ct, i) rt.setValue("DotX", ct, yA[i]) rt.setValue("DotY", ct, xA[i]) rt.setValue("DotZ", ct, zA[i]) rt.setValue("Ch2_TotalIntensity", ct, stats.area * stats.mean) rt.setValue("Ch2_MeanIntensity", ct, stats.mean) rt.setValue("Ch3_TotalIntensity", ct, statsch3.area * statsch3.mean) rt.setValue("Ch3_meanIntensity", ct, statsch3.mean) ct += 1 rt.show("Dot Intensity") #AREA, AREA_FRACTION, CENTER_OF_MASS, CENTROID, CIRCULARITY, ELLIPSE, FERET, #INTEGRATED_DENSITY, INVERT_Y, KURTOSIS, LABELS, LIMIT, MAX_STANDARDS, MEAN, #MEDIAN, MIN_MAX, MODE, PERIMETER, RECT, SCIENTIFIC_NOTATION, SHAPE_DESCRIPTORS, #SKEWNESS, SLICE, STACK_POSITION, STD_DEV
def main(): rt = RT.open2(table_file.getAbsolutePath()) if not rt: return log(" --- --- --- ") log("Loaded %s" % table_file.getAbsolutePath()) log("Loading column lists...") # Get column indices from imported file headings = getColumnHeadings(rt) id_col = getColumnIndex(headings, "TID") t_col = getColumnIndex(headings, "t [") d2p_col = getColumnIndex(headings, "D2P [") angle_col = getColumnIndex(headings, u'\u03B1 [deg]') delta_col = getColumnIndex(headings, u'\u0394\u03B1 [deg]') if angle_col == RT.COLUMN_NOT_FOUND: log("Failed to detect index for angle column. Re-trying...") angle_col = getColumnIndex(headings, u'? [deg]') if delta_col == RT.COLUMN_NOT_FOUND: log("Failed to detect index for delta angle column. Re-trying...") delta_col = getColumnIndex(headings, u'?? [deg]') log("Last column index is %s" % rt.getLastColumn()) if RT.COLUMN_NOT_FOUND in (id_col, d2p_col, delta_col, angle_col): uiservice.showDialog("Error: Some key columns were not found!", "Invalid Table?") return log("Settings: BOUT_WINDOW= %s, MIN_D2P= %s, DEF_FRAME_INTERVAL= %s" % (BOUT_WINDOW, '{0:.4f}'.format(MIN_D2P), DEF_FRAME_INTERVAL)) # Store all data on dedicated lists track_id_rows = rt.getColumnAsDoubles(id_col) d2p_rows = rt.getColumnAsDoubles(d2p_col) angle_rows = rt.getColumnAsDoubles(angle_col) delta_rows = rt.getColumnAsDoubles(delta_col) t_rows = rt.getColumnAsDoubles(t_col) # Assess n of data points and extract unique path ids n_rows = len(track_id_rows) row_indices = range(n_rows) track_ids = set(track_id_rows) n_tracks = len(track_ids) log("Table has %g rows" % n_rows) log("Table has %g tracks" % n_tracks) log("Parsing tracks...") for track_id in track_ids: for row, next_row in zip(row_indices, row_indices[1:]): if track_id_rows[row] != track_id: continue if not isNumber(angle_rows[row]): rt.setValue("FLAG", row, "NA") continue lower_bound = max(0, row - BOUT_WINDOW + 1) upper_bound = min(n_rows-1, row + BOUT_WINDOW) win_d2p = [] for _ in range(lower_bound, upper_bound): win_d2p.append(d2p_rows[row]) if sum(win_d2p) <= MIN_D2P * len(win_d2p): rt.setValue("FLAG", row, 0) else: current_angle = angle_rows[row] next_angle = angle_rows[next_row] current_delta = delta_rows[row] flag = -1 if current_angle < 0 else 1 delta_change = (abs(current_delta) > 90) same_sign = ((current_angle<0) == (next_angle<0)) if delta_change and not same_sign: flag *= -1 rt.setValue("FLAG", row, flag) if next_row == n_rows - 1: rt.setValue("FLAG", next_row, flag) if rt.save(table_file.getAbsolutePath()): log("Processed table successfully saved (file overwritten)") else: log("Could not override input file. Displaying it...") rt.show(table_file.name) log("Creating onset table...") onset_rt = RT() onset_rt.showRowNumbers(False) frame_int = DEF_FRAME_INTERVAL if "table" in frame_rate_detection: frame_int = getFrameIntervalFromTable(row_indices, track_id_rows, t_rows) elif "image" in frame_rate_detection: frame_int = getFrameIntervalFromImage(image_file.getAbsolutePath()) else: log("Using default frame rate") for track_id in track_ids: for prev_row, row in zip(row_indices, row_indices[1:]): if not track_id in (track_id_rows[prev_row], track_id_rows[row]): continue flag = rt.getValue("FLAG", row) if not isNumber(flag): continue flag = int(flag) if flag == 0: continue if flag == 1 or flag == -1: srow = onset_rt.getCounter() onset_rt.incrementCounter() onset_rt.setValue("TID", srow, track_id) from_frame = int(t_rows[prev_row]/frame_int) + 1 to_frame = int(t_rows[row]/frame_int) + 1 onset_rt.setValue("First disp. [t]", srow, "%s to %s" % (t_rows[prev_row], t_rows[row])) onset_rt.setValue("First disp. [frames]", srow, "%s to %s" % (from_frame, to_frame)) onset_rt.setValue("ManualTag", srow, "") break out_path = suffixed_path(table_file.getAbsolutePath(), "ManualTagging") if onset_rt.save(out_path): log("Summary table successfully saved: %s" % out_path) else: log("File not saved... Displaying onset table") onset_rt.show("Onsets %s" % table_file.name)
my_gmd = Log().value(gmd_nm) my_gsd = Log().value(gsd) distn = LogNormalDistribution(my_gmd, my_gsd) the_sample = distn.sample() return(the_sample) tic = time.time() n_samples = 2500 rt = ResultsTable(n_samples) rt.setHeading(0, "num") rt.setHeading(1, "ECD nm") for x in range(0, n_samples): my_sample = gen_random_lognormal_particle(50.0, 1.2) rt.setValue(0, x, x+1) rt.setValue(1, x, my_sample) rt.show("Results") IJ.saveAs("Results", csv_out) toc = time.time() elapsed = toc - tic print("generated %g particles" % n_samples) print("completed in %g sec" % elapsed ) print("saved here:") print("%s" % csv_out ) print("done...") rt.reset()
def main(tableName, showPlot): image = IJ.getImage(); roi = image.getRoi() if not roi: center = image.getWidth() / 2, image.getHeight() / 2 else: center = roi.getXBase(), roi.getYBase(); table = ResultsTable.getResultsTable(tableName) rma = RadialMovementAnalyzer(table, center) radialDistances = rma.getDeltaRadialDistancePerTrack() distances = rma.getDistances() frames = rma.getFrames() travelledDistances = rma.getTravelledDistances() TABLE_NAME = "Distance from " + str(center) rt = ResultsTable.getResultsTable(TABLE_NAME) if not rt: rt = ResultsTable() for index, dist in enumerate(radialDistances): row = rt.getCounter() rt.setValue("label", row, tableName) rt.setValue("track ID", row, rma.trackIDs[index]) rt.setValue("total augmentation of distance from center", row, dist) rt.setValue("distance start to end", row, distances[index]) rt.setValue("travelled distance", row, travelledDistances[index]) rt.setValue("nr. of frames", row, frames[index]) if not distances[index] == 0: rt.setValue("total augmentation / distance start to end", row, dist / distances[index]) else: rt.setValue("total augmentation / distance start to end", row, float("nan")) if not travelledDistances[index] ==0: rt.setValue("total augmentation / travelled distance", row, dist / travelledDistances[index]) else: rt.setValue("total augmentation / travelled distance", row, float("nan")) rt.setValue("mean speed", row, travelledDistances[index] / frames[index]) rt.setValue("mean outward speed", row, dist / frames[index]) rt.show(TABLE_NAME) if showPlot: plot(distances, radialDistances, center)
# 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') std = spot.getFeature('STANDARD_DEVIATION') estdia = spot.getFeature('ESTIMATED_DIAMETER') 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)) table.setValue("TRACK_ID", rowNumber, id) table.setValue("POSITION_X", rowNumber, x) table.setValue("POSITION_Y", rowNumber, y) table.setValue("FRAME", rowNumber, t) table.setValue("MEAN_INTENSITY", rowNumber, mean) table.setValue("STANDARD_DEVIATION", rowNumber, std) table.setValue("SNR", rowNumber, snr) rowNumber = rowNumber + 1 # roi1 = PointRoi(x/dx, y/dy) # roi1.setPosition(int(t)) # rm.add(imp, roi1, nextRoi) # nextRoi = nextRoi+1 frame = table.getColumn(3) mean = table.getColumn(4)
class MandersPlugin(ImageListener, WindowAdapter): def __init__(self): self.imp = None self.preview = None self.createMainWindow() self.cells = None self.files = [] self.results = ResultsTable() ImagePlus.addImageListener(self) self.selectInputDir() self.selectOutputDir() self.pairs = [] self.methods = [] self.processNextFile() def selectInputDir(self): inputDialog = DirectoryChooser("Please select a directory contaning your images") inputDir = inputDialog.getDirectory() for imageFile in os.listdir(inputDir): self.files.append(inputDir + imageFile) def selectOutputDir(self): outputDialog = DirectoryChooser("Please select a directory to save your results") self.outputDir = outputDialog.getDirectory() def closeImage(self): if self.imp is not None: self.imp.close() self.imp = None if self.preview is not None: self.preview.close() self.preview = None def openImage(self, imageFile): try: images = BF.openImagePlus(imageFile) self.imp = images[0] except UnknownFormatException: return None if self.imp.getNChannels() < 2: IJ.error("Bad image format", "Image must contain at lease 2 channels!") return None if not self.pairs or \ not self.methods: self.getOptionsDialog(self.imp) title = self.imp.title self.imp.title = title[:title.rfind('.')] return self.imp def getOptionsDialog(self, imp): thr_methods = ["None", "Default", "Huang", "Intermodes", "IsoData", "Li", "MaxEntropy","Mean", "MinError(I)", "Minimum", "Moments", "Otsu", "Percentile", "RenyiEntropy", "Shanbhag" , "Triangle", "Yen"] gd = GenericDialog("Please select channels to collocalize") for i in range(1, imp.getNChannels() + 1): gd.addChoice("Threshold method for channel %i" % i, thr_methods, "None") gd.showDialog() if gd.wasCanceled(): self.exit() channels = [] for i in range(1, imp.getNChannels() + 1): method = gd.getNextChoice() self.methods.append(method) if method != "None": channels.append(i) for x in channels: for y in channels: if x < y: self.pairs.append((x, y)) def processNextFile(self): if self.files: imageFile = self.files.pop(0) return self.processFile(imageFile) else: return False def processFile(self, imageFile): imp = self.openImage(imageFile) if imp is not None: cell = Cell(imp.NSlices, 1) self.cells = DelegateListModel([]) self.cells.append(cell) self.showMainWindow(self.cells) if self.checkbox3D.isSelected(): self.displayImage(imp) else: self.displayImage(imp, False) self.preview = self.previewImage(imp) self.displayImage(self.preview) return True else: return self.processNextFile() def displayImage(self, imp, show = True): imp.setDisplayMode(IJ.COMPOSITE) enhancer = ContrastEnhancer() enhancer.setUseStackHistogram(True) splitter = ChannelSplitter() for c in range(1, imp.getNChannels() + 1): imp.c = c enhancer.stretchHistogram(imp, 0.35) if show: imp.show() def previewImage(self, imp): roi = imp.getRoi() splitter = ChannelSplitter() channels = [] for c in range(1, imp.getNChannels() + 1): channel = ImagePlus("Channel %i" % c, splitter.getChannel(imp, c)) projector = ZProjector(channel) projector.setMethod(ZProjector.MAX_METHOD) projector.doProjection() channels.append(projector.getProjection()) image = RGBStackMerge.mergeChannels(channels, False) image.title = imp.title + " MAX Intensity" image.luts = imp.luts imp.setRoi(roi) return image def getCroppedChannels(self, imp, cell): splitter = ChannelSplitter() imp.setRoi(None) if cell.mode3D: cropRoi = cell.getCropRoi() else: cropRoi = cell.roi if cropRoi is None: return None crop = cropRoi.getBounds() channels = [] for c in range(1, imp.getNChannels() + 1): slices = ImageStack(crop.width, crop.height) channel = splitter.getChannel(imp, c) for z in range(1, channel.getSize() + 1): zslice = channel.getProcessor(z) zslice.setRoi(cropRoi) nslice = zslice.crop() if cell.mode3D: oroi = cell.slices[z - 1].roi else: oroi = cell.roi if oroi is not None: roi = oroi.clone() bounds = roi.getBounds() roi.setLocation(bounds.x - crop.x, bounds.y - crop.y) nslice.setColor(Color.black) nslice.fillOutside(roi) slices.addSlice(nslice) channels.append(ImagePlus("Channel %i" % c, slices)) return channels def getThreshold(self, imp, method): thresholder = Auto_Threshold() duplicator = Duplicator() tmp = duplicator.run(imp) return thresholder.exec(tmp, method, False, False, True, False, False, True) def getContainer(self, impA, impB): imgA = ImagePlusAdapter.wrap(impA) imgB = ImagePlusAdapter.wrap(impB) return DataContainer(imgA, imgB, 1, 1, "imageA", "imageB") def getManders(self, imp, cell): ### Crop channels according to cell mask channels = self.getCroppedChannels(imp, cell) if channels is None: return None ### Calculate channel thresholds thrs = [] thrimps = [] for c, method in enumerate(self.methods): if method != "None": thr, thrimp = self.getThreshold(channels[c], method) else: thr, thrimp = None, None thrs.append(thr) thrimps.append(thrimp) ### Calculate manders colocalization manders = MandersColocalization() raws = [] thrds = [] for chA, chB in self.pairs: container = self.getContainer(channels[chA - 1], channels[chB - 1]) img1 = container.getSourceImage1() img2 = container.getSourceImage2() mask = container.getMask() cursor = TwinCursor(img1.randomAccess(), img2.randomAccess(), Views.iterable(mask).localizingCursor()) rtype = img1.randomAccess().get().createVariable() raw = manders.calculateMandersCorrelation(cursor, rtype) rthr1 = rtype.copy() rthr2 = rtype.copy() rthr1.set(thrs[chA - 1]) rthr2.set(thrs[chB - 1]) cursor.reset() thrd = manders.calculateMandersCorrelation(cursor, rthr1, rthr2, ThresholdMode.Above) raws.append(raw) thrds.append(thrd) return (channels, thrimps, thrs, raws, thrds) def saveMultichannelImage(self, title, channels, luts): tmp = RGBStackMerge.mergeChannels(channels, False) tmp.luts = luts saver = FileSaver(tmp) saver.saveAsTiffStack(self.outputDir + title + ".tif") tmp.close() def createMainWindow(self): self.frame = JFrame('Select cells and ROIs', defaultCloseOperation = JFrame.DISPOSE_ON_CLOSE ) self.frame.setLayout(GridBagLayout()) self.frame.addWindowListener(self) self.frame.add(JLabel("Cells"), GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, Insets(5, 2, 2, 0), 0, 0 )) self.cellList = JList(DelegateListModel([]), selectionMode = ListSelectionModel.SINGLE_SELECTION, cellRenderer = MyRenderer(), selectedIndex = 0, valueChanged = self.selectCell ) self.frame.add(JScrollPane(self.cellList), GridBagConstraints(0, 1, 1, 5, .5, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(0, 2, 2, 0), 0, 0 )) self.frame.add(JButton('Add cell', actionPerformed = self.addCell), GridBagConstraints(1, 2, 1, 2, 0, .25, GridBagConstraints.CENTER, GridBagConstraints.NONE, Insets(0, 0, 0, 0), 0, 0 )) self.frame.add(JButton('Remove cell', actionPerformed = self.removeCell), GridBagConstraints(1, 4, 1, 2, 0, .25, GridBagConstraints.CENTER, GridBagConstraints.NONE, Insets(0, 5, 0, 5), 0, 0 )) self.frame.add(JLabel("Slices"), GridBagConstraints(0, 6, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, Insets(5, 2, 2, 0), 0, 0 )) self.sliceList = JList(DelegateListModel([]), selectionMode = ListSelectionModel.SINGLE_SELECTION, cellRenderer = MyRenderer(), selectedIndex = 0, valueChanged = self.selectSlice ) self.frame.add(JScrollPane(self.sliceList), GridBagConstraints(0, 7, 1, 5, .5, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(0, 2, 2, 0), 0, 0 )) self.frame.add(JButton('Update ROI', actionPerformed = self.updateSlice), GridBagConstraints(1, 8, 1, 2, 0, .25, GridBagConstraints.CENTER, GridBagConstraints.NONE, Insets(0, 0, 0, 0), 0, 0 )) self.frame.add(JButton('Done', actionPerformed = self.doneSelecting), GridBagConstraints(1, 10, 1, 2, 0, .25, GridBagConstraints.CENTER, GridBagConstraints.NONE, Insets(0, 0, 0, 0), 0, 0 )) self.checkbox3D = JCheckBox('3D selection mode', True, actionPerformed=self.toggle3D) self.frame.add(self.checkbox3D, GridBagConstraints(0, 13, 2, 1, 0, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(0, 0, 0, 0), 0, 0 )) def showMainWindow(self, cells = None): if cells is not None: self.cellList.model = cells if cells: self.cellList.selectedIndex = 0 self.frame.pack() self.frame.visible = True def hideMainWindow(self): self.frame.visible = False def closeMainWindow(self): self.frame.dispose() def toggle3D(self, event): mode3D = self.checkbox3D.isSelected() if mode3D: self.sliceList.enabled = True if self.imp is not None: self.imp.show() if self.preview is not None: self.preview.hide() else: self.sliceList.enabled = False if self.preview is None: self.preview = self.previewImage(self.imp) self.displayImage(self.preview) else: self.preview.show() if self.imp is not None: self.imp.hide() selectedCell = self.cellList.selectedIndex if selectedCell >= 0: cell = self.cells[selectedCell] self.sliceList.model = cell.slices self.sliceList.selectedIndex = 0 def addCell(self, event): size = len(self.cells) if (size > 0): last = self.cells[size - 1] n = last.n + 1 else: n = 1 self.cells.append(Cell(self.imp.NSlices, n)) self.cellList.selectedIndex = size def removeCell(self, event): selected = self.cellList.selectedIndex if selected >= 0: self.cells.remove(self.cells[selected]) if (selected >= 1): self.cellList.selectedIndex = selected - 1 else: self.cellList.selectedIndex = 0 def selectCell(self, event): selected = self.cellList.selectedIndex if selected >= 0: cell = self.cells[selected] self.sliceList.model = cell.slices self.sliceList.selectedIndex = 0 else: self.sliceList.model = DelegateListModel([]) if self.preview is not None: self.preview.setRoi(cell.roi) def selectSlice(self, event): selectedCell = self.cellList.selectedIndex selectedSlice = self.sliceList.selectedIndex if selectedCell >= 0 and selectedSlice >= 0: cell = self.cells[selectedCell] image = self.imp mode3D = self.checkbox3D.isSelected() if image is not None and cell is not None and mode3D: roi = cell.slices[selectedSlice].roi if (image.z - 1 != selectedSlice): image.z = selectedSlice + 1 image.setRoi(roi, True) if self.preview is not None and not mode3D: self.preview.setRoi(cell.roi, True) def updateSlice(self, event): if self.checkbox3D.isSelected(): self.updateSlice3D(self.imp) else: self.updateSlice2D(self.preview) def updateSlice3D(self, imp): selectedCell = self.cellList.selectedIndex selectedSlice = self.sliceList.selectedIndex if selectedCell >= 0 and selectedSlice >= 0 and imp is not None: cell = self.cells[selectedCell] impRoi = imp.getRoi() if cell is not None and impRoi is not None: index = selectedSlice + 1 roi = ShapeRoi(impRoi, position = index) cell.mode3D = True cell.name = "Cell %i (3D)" % cell.n cell.slices[selectedSlice].roi = roi if (index + 1 <= len(cell.slices)): imp.z = index + 1 self.cellList.repaint(self.cellList.getCellBounds(selectedCell, selectedCell)) self.sliceList.repaint(self.sliceList.getCellBounds(selectedSlice, selectedSlice)) def updateSlice2D(self, imp): selectedCell = self.cellList.selectedIndex if selectedCell >= 0 and imp is not None: cell = self.cells[selectedCell] impRoi = imp.getRoi() if cell is not None and impRoi is not None: roi = ShapeRoi(impRoi, position = 1) cell.mode3D = False cell.name = "Cell %i (2D)" % cell.n cell.roi = roi self.cellList.repaint(self.cellList.getCellBounds(selectedCell, selectedCell)) def imageOpened(self, imp): pass def imageClosed(self, imp): pass def imageUpdated(self, imp): if self.checkbox3D.isSelected(): if imp is not None: selectedCell = self.cellList.selectedIndex selectedSlice = imp.z - 1 if imp == self.imp and selectedSlice != self.sliceList.selectedIndex: self.sliceList.selectedIndex = selectedSlice def doneSelecting(self, event): oluts = self.imp.luts luts = [] channels = [] for c, method in enumerate(self.methods): if method != "None": luts.append(oluts[c]) channels.append(c) for cell in self.cells: manders = self.getManders(self.imp, cell) if manders is not None: chimps, thrimps, thrs, raws, thrds = manders index = self.cells.index(cell) + 1 title = "Cell_%i-" % index + self.imp.title self.saveMultichannelImage(title, chimps, oluts) title = "Cell_%i_thrd-" % index + self.imp.title self.saveMultichannelImage(title, thrimps, luts) self.results.incrementCounter() row = self.results.getCounter() - 1 for i, thr in enumerate(thrs): if thr is not None: self.results.setValue("Threshold %i" % (i + 1), row, int(thr)) for i, pair in enumerate(self.pairs): self.results.setValue("%i-%i M1 raw" % pair, row, float(raws[i].m1)) self.results.setValue("%i-%i M2 raw" % pair, row, float(raws[i].m2)) self.results.setValue("%i-%i M1 thrd" % pair, row, float(thrds[i].m1)) self.results.setValue("%i-%i M2 thrd" % pair, row, float(thrds[i].m2)) self.closeImage() if not self.processNextFile(): print "All done - happy analysis!" self.results.show("Manders collocalization results") self.exit() def windowClosing(self, e): print "Closing plugin - BYE!!!" self.exit() def exit(self): ImagePlus.removeImageListener(self) self.closeImage() self.closeMainWindow()
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