Exemplo n.º 1
0
def getFlipArray(maskPAImgPlus):
    """Given the PA-aligned mask image, return a list of booleans, indicating whether or not we should flip the corresponding index"""
    maskPAImgPlus.show()
    #	IJ.run(maskPAImgPlus, "Shape Smoothing", "relative_proportion_fds=15 absolute_number_fds=2 keep=[Relative_proportion of FDs] stack");

    IJ.run("Set Measurements...", "shape")
    IJ.setThreshold(maskPAImgPlus, 1, 1000, "No Update")
    stk = maskPAImgPlus.getStack()

    tableLeft = ResultsTable()
    PA.setResultsTable(tableLeft)
    IJ.makeRectangle(0, 0,
                     maskPAImgPlus.getWidth() / 2 - 5,
                     maskPAImgPlus.getHeight())
    IJ.run(maskPAImgPlus, "Analyze Particles...", "stack")

    tableRight = ResultsTable()
    PA.setResultsTable(tableRight)
    IJ.makeRectangle(maskPAImgPlus.getWidth() / 2 - 5, 0,
                     maskPAImgPlus.getWidth() / 2 + 5,
                     maskPAImgPlus.getHeight())
    IJ.run(maskPAImgPlus, "Analyze Particles...", "stack")
    maskPAImgPlus.hide()

    IJ.resetThreshold(maskPAImgPlus)

    leftCirc = [tableLeft.getValue("Circ.", i) for i in range(stk.getSize())]
    rightCirc = [tableRight.getValue("Circ.", i) for i in range(stk.getSize())]
    return [leftCirc[i] < rightCirc[i] for i in range(len(leftCirc))]
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)
Exemplo n.º 3
0
    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)
Exemplo n.º 4
0
def getTable():
    ''' Check if a table exists otherwise open a new one'''

    ## Check if we can get a table window
    if IJ.getFullVersion() >= "1.53g":
        # try to get any active table
        tableWindow = WindowManager.getActiveTable(
        )  # this function requires 1.53g (or at least not working with 1.53c), return None if no table

    else:
        # Fallback on fetching either a window called Annotations or Annotations.csv as in previous plugin version
        win = WindowManager.getWindow("Annotations")
        win2 = WindowManager.getWindow(
            "Annotations.csv")  # upon saving it adds this extension

        if win:
            tableWindow = win

        elif win2:
            tableWindow = win2

        else:
            tableWindow = None

    ## If a table window then get its table, otherwise new table. In this case, its name is set later
    return tableWindow.getResultsTable() if tableWindow else ResultsTable()
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!"
Exemplo n.º 6
0
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")
Exemplo n.º 7
0
def analyze(imp, min_area):
    MAXSIZE = 1000000000000
    MINCIRCULARITY = 0.0
    MAXCIRCULARITY = 1.
    
    options = PA.SHOW_MASKS 
    
    temp_results = ResultsTable()
    
    p = PA(options, PA.AREA + PA.MEAN, temp_results, min_area, MAXSIZE, MINCIRCULARITY, MAXCIRCULARITY)
    p.setHideOutputImage(True)

    p.analyze(imp)

    if temp_results.getCounter() == 0:
        areas   = []
        signals = []
    else:
        areas   = list(temp_results.getColumn(0))
        signals = list(temp_results.getColumn(1))
    
    count  = len(areas)
    area   = sum(areas)

    total = 0
    if area > 0:
        total  = sum([a*s for a,s in zip(areas, signals)]) / area
      

    return p.getOutputImage(), count, area, total
Exemplo n.º 8
0
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()
Exemplo n.º 10
0
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)
 def setUp(self):
     unittest.TestCase.setUp(self)
     rt = ResultsTable()
     rt.incrementCounter()
     rt.addLabel('LABEL', 'ID00002')
     rt.addValue('ID', 2)
     rt.addValue('TRACK_ID', 2)
     rt.addValue('QUALITY', 1)
     rt.addValue('POSITION_X', 738.9)
     rt.addValue('POSITION_Y', 670.0)
     rt.addValue('POSITION_Z', 0)
     rt.addValue('POSITION_T', 0)
     rt.incrementCounter()
     rt.addLabel('LABEL', 'ID00003')
     rt.addValue('ID', 3)
     rt.addValue('TRACK_ID', 3)
     rt.addValue('QUALITY', 1)
     rt.addValue('POSITION_X', 672.1)
     rt.addValue('POSITION_Y', 729.3)
     rt.addValue('POSITION_Z', 0)
     rt.addValue('POSITION_T', 0)
     rt.incrementCounter()
     rt.addLabel('LABEL', 'ID00001')
     rt.addValue('ID', 31)
     rt.addValue('TRACK_ID', 1)
     rt.addValue('QUALITY', 1)
     rt.addValue('POSITION_X', 953.2)
     rt.addValue('POSITION_Y', 803.5)
     rt.addValue('POSITION_Z', 0)
     rt.addValue('POSITION_T', 1)
     rt.incrementCounter()
     rt.addLabel('LABEL', 'ID000032')
     rt.addValue('ID', 32)
     rt.addValue('TRACK_ID', 2)
     rt.addValue('QUALITY', 1)
     rt.addValue('POSITION_X', 739.5)
     rt.addValue('POSITION_Y', 665.0)
     rt.addValue('POSITION_Z', 0)
     rt.addValue('POSITION_T', 1)
     rt.incrementCounter()
     rt.addLabel('LABEL', 'ID000033')
     rt.addValue('ID', 33)
     rt.addValue('TRACK_ID', 3)
     rt.addValue('QUALITY', 1)
     rt.addValue('POSITION_X', 667.0)
     rt.addValue('POSITION_Y', 729.8)
     rt.addValue('POSITION_Z', 0)
     rt.addValue('POSITION_T', 1)
     rt.incrementCounter()
     rt.addLabel('LABEL', 'ID000061')
     rt.addValue('ID', 61)
     rt.addValue('TRACK_ID', 1)
     rt.addValue('QUALITY', 1)
     rt.addValue('POSITION_X', 959.0)
     rt.addValue('POSITION_Y', 805.5)
     rt.addValue('POSITION_Z', 0)
     rt.addValue('POSITION_T', 2)
     self.table = rt
Exemplo n.º 12
0
    def analyzeParticles(imp, minsize, maxsize, mincirc, maxcirc,
                         filename='Test.czi',
                         addROIManager=True,
                         headless=True,
                         exclude=True):

        if addROIManager is True:

            if exclude is False:
                options = PA.SHOW_ROI_MASKS \
                    + PA.SHOW_RESULTS \
                    + PA.DISPLAY_SUMMARY \
                    + PA.ADD_TO_MANAGER \
                    + PA.ADD_TO_OVERLAY \

            if exclude is True:
                options = PA.SHOW_ROI_MASKS \
                    + PA.SHOW_RESULTS \
                    + PA.DISPLAY_SUMMARY \
                    + PA.ADD_TO_MANAGER \
                    + PA.ADD_TO_OVERLAY \
                    + PA.EXCLUDE_EDGE_PARTICLES

        if addROIManager is False:

            if exclude is False:
                options = PA.SHOW_ROI_MASKS \
                    + PA.SHOW_RESULTS \
                    + PA.DISPLAY_SUMMARY \
                    + PA.ADD_TO_OVERLAY \

            if exclude is True:
                options = PA.SHOW_ROI_MASKS \
                    + PA.SHOW_RESULTS \
                    + PA.DISPLAY_SUMMARY \
                    + PA.ADD_TO_OVERLAY \
                    + PA.EXCLUDE_EDGE_PARTICLES

        measurements = PA.STACK_POSITION \
            + PA.LABELS \
            + PA.AREA \
            + PA.RECT \

        results = ResultsTable()
        p = PA(options, measurements, results, minsize, maxsize, mincirc, maxcirc)
        p.setHideOutputImage(True)
        particlestack = ImageStack(imp.getWidth(), imp.getHeight())

        for i in range(imp.getStackSize()):
            imp.setSliceWithoutUpdate(i + 1)
            ip = imp.getProcessor()
            #IJ.run(imp, "Convert to Mask", "")
            p.analyze(imp, ip)
            mmap = p.getOutputImage()
            particlestack.addSlice(mmap.getProcessor())

        return particlestack, results
Exemplo n.º 13
0
def writeCSV(filePath, results, header):
    """ Write a table as an csv file """
    rt = ResultsTable()
    for i in range(len(results[1])):
        rt.incrementCounter()
        for j in range(len(results)):
            rt.addValue(str(header[j]), results[j][i])
    rt.show("Results")
    rt.saveAs(filePath)
Exemplo n.º 14
0
def show_as_table(title, data, order=[]):
    """Helper function to display group and data information as a ResultsTable"""
    table = ResultsTable()
    for d in data:
        table.incrementCounter()
        order = [k for k in order]
        order.extend([k for k in d.keys() if not d in order])
        for k in order:
            table.addValue(k, d[k])
    table.show(title)
Exemplo n.º 15
0
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)
Exemplo n.º 16
0
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 analyse():
	rt = ResultsTable()
	ol = Overlay()

	masks = [getMask(imp, c) for c in range(1, C+1)]
	DAPImask = masks[0]
	IJ.run(DAPImask, "Create Selection", "")
	DAPIRoi = DAPImask.getRoi()
	rois = ShapeRoi(DAPIRoi).getRois()
	for c,mask in enumerate(masks):
		if c==0:
Exemplo n.º 18
0
def process(inputpath, outputpath):

    imp = IJ.openImage(inputpath)
    IJ.run(
        imp, "Properties...",
        "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001"
    )

    IJ.setThreshold(imp, t1, 255)
    #imp.show()
    #WaitForUserDialog("Title", "Look at image").show()
    IJ.run(imp, "Convert to Mask", "")
    IJ.run(imp, "Watershed", "")

    # Counts and measures the area of particles and adds them to a table called areas. Also adds them to the ROI manager

    table = ResultsTable()
    roim = RoiManager(True)
    ParticleAnalyzer.setRoiManager(roim)
    pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA,
                          table, 50, 9999999999999999, 0.2, 1.0)
    pa.setHideOutputImage(True)
    pa.analyze(imp)

    imp.changes = False
    imp.close()

    areas = table.getColumn(0)

    summary = {}

    if areas:

        summary['Image'] = filename
        summary['Nuclei.count'] = len(areas)
        summary['Area.Covered'] = sum(areas)

    fieldnames = list(summary.keys())

    with open(outputpath, 'a') as csvfile:

        writer = csv.DictWriter(csvfile,
                                fieldnames=fieldnames,
                                extrasaction='ignore',
                                lineterminator='\n')
        if os.path.getsize(outputDirectory + "/" + outputname + ".csv") < 1:
            writer.writeheader()
        writer.writerow(summary)
def run():
  global srcFile, ext, numberOfWidthMeasurements
  IJ.run("Set Measurements...", "area mean standard modal min centroid center perimeter bounding fit shape feret's integrated median skewness kurtosis area_fraction display redirect=None decimal=3");
  IJ.setForegroundColor(255,255,255);
  IJ.setBackgroundColor(0,0,0);  
  IJ.run("Options...", "iterations=1 count=1 black");
  table = ResultsTable()
  srcDir = srcFile.getAbsolutePath()
  for root, directories, filenames in os.walk(srcDir):
    for filename in filenames:
      # Check for file extension
      if not filename.endswith(ext):
        continue
      # Check for file name pattern
      process(srcDir, root, filename, table, numberOfWidthMeasurements)
  table.save(os.path.join(srcDir, 'Results.xls'))
Exemplo n.º 20
0
    def createAngleTable(self, roi):
        polygon = roi.getPolygon()
        xPoints = polygon.xpoints
        yPoints = polygon.ypoints

        nPoints = polygon.npoints
        table = ResultsTable()
        firstAngle = Math.atan2(yPoints[0], xPoints[0])
        plot = Plot(str(roi.getName()) + " Angle", "--", "angle")

        angles = []
        derivative = []
        derivativeSign = []
        posDerivative = 0
        negDerivative = 0

        for i in range(nPoints):
            x = xPoints[i]
            y = yPoints[i]
            angle = Math.atan2(y, x)

            angles.append(angle - firstAngle)
            if i == 0:
                continue

            derivative.append(angle - angles[-2])
            derivativeSign.append(Math.signum(derivative[-1]))
            if derivativeSign[-1] > 0:
                posDerivative = posDerivative + 1
            else:
                negDerivative = negDerivative + 1

        maxSign = max(posDerivative, negDerivative)
        minSign = min(posDerivative, negDerivative)

        print("--" + str(roi.getName()))
        signRatio = float(minSign) / float(maxSign)
        print("Min Sign = " + str(minSign))
        print("Max Sign = " + str(maxSign))
        print("Sign Ratio = " + str(signRatio))
        plot.add("filled", derivativeSign)
        plot.show()

        if signRatio < 1.1:
            # table.show(str( roi.getName())+" Angle")
            return True
        return False
Exemplo n.º 21
0
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 countParticles(imp, roim, minSize, maxSize, minCircularity, maxCircularity):
	# Create a table to store the results
	table = ResultsTable()
	
	# Create the particle analyzer
	pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA|Measurements.MEAN, table, minSize, maxSize, minCircularity, maxCircularity)
	#pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA|Measurements.MEAN, table, 10, Double.POSITIVE_INFINITY, 0.5, 1.0)
	#pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA|Measurements.MEAN, table, 5, 6, 0.5, 1.0)
	pa.setRoiManager(roim)
	pa.setHideOutputImage(True)

	if pa.analyze(imp):
		print "All ok"
	else:
 		print "There was a problem in analyzing", blobs

 	areas = table.getColumn(0)
	intensities = table.getColumn(1)

	if ( (areas!=None) and (intensities!=None)):
 		for area, intensity in zip(areas,intensities): print str(area)+": "+str(intensity)
Exemplo n.º 23
0
def myResults(results):
    myResultsTable = ResultsTable()
    for idx, graph in enumerate(results.getGraph()):
        for edge in graph.getEdges():
            edgeLength = edge.getLength()
            v1 = edge.getV1()
            v2 = edge.getV2()
            dist = euclideanDistance(v1, v2)
            #print('v1:', type(v1), v1.getPoints())
            #
            myResultsTable.incrementCounter()  # add a row to results table
            myResultsTable.addValue('graphID', idx)
            myResultsTable.addValue('length_3d', edgeLength)
            myResultsTable.addValue('dist', dist)
            if dist > 0:
                myResultsTable.addValue('tort', edgeLength / dist)
            else:
                myResultsTable.addValue('tort', 'inf')

    myResultsTable.setPrecision(6)
    myResultsTable.show('samiSkel_results')
Exemplo n.º 24
0
def countParticles(imp, roim, minSize, maxSize, minCircularity,
                   maxCircularity):
    # Create a table to store the results
    table = ResultsTable()

    # Create the particle analyzer
    pa = ParticleAnalyzer(
        ParticleAnalyzer.ADD_TO_MANAGER,
        Measurements.AREA | Measurements.MEAN | Measurements.ELLIPSE, table,
        minSize, maxSize, minCircularity, maxCircularity)
    pa.setRoiManager(roim)
    pa.setHideOutputImage(True)

    if pa.analyze(imp):
        print "All ok"
    else:
        print "There was a problem in analyzing", blobs

    areas = table.getColumn(0)
    intensities = table.getColumn(1)
    majors = table.getColumn(2)
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)
Exemplo n.º 26
0
def removeSmallCCs(image):

	MINSIZE = 1000
	MAXSIZE = 1000000

	options = PA.SHOW_ROI_MASKS 
			
	
	results = ResultsTable()
	
	p = PA(options, PA.STACK_POSITION + PA.LABELS + PA.AREA + PA.PERIMETER + PA.CIRCULARITY, results, MINSIZE, MAXSIZE)
	p.setHideOutputImage(True)
	p.analyze(image)
	mmap = p.getOutputImage()
	mip = mmap.getProcessor() 
	mip.threshold(0)
	img = ImagePlus("rods_processed", mip)
	IJ.run(img, "8-bit", "") 
	IJ.run(img, "Make Binary", "method=Default background=Dark black")
	

	return img
Exemplo n.º 27
0
def AnalyzeParticle(IMP):
    rm = RoiManager().getInstance2()
    rt = ResultsTable()

    #再現性確保のために最終的には実装
    #IJ.run("Set Measurements...","area  centroid fit redirect=None decimal=3")

    #https://imagej.nih.gov/ij/developer/api/constant-values.html#ij.plugin.filter.ParticleAnalyzer.SHOW_RESULTS
    #表示オプション無し、resultは全部選択
    PA = ParticleAnalyzer(0 , 1043199 , rt, 10000, 300000, 0.2, 1.0)
    PA.setRoiManager(rm)
    PA.analyze(IMP)

    #IJ.run(IMP, "Analyze Particles...", "display clear include add")
    rm.runCommand("Save", "C:/Users/For  Programming/Documents/Python Scripts/OutletHDD/aaa.zip")
    rt.saveAs("C:/Users/For  Programming/Documents/Python Scripts/OutletHDD/aaa.csv")


    #最後に全ての結果をCloseする。
    #写真を先に消さないとバグる。
    IMP.close()
    rm.close()
    rt.reset()
def quantify(quantgfx, labelgfx, table, nFrame, originalTitle):
    results = ResultsTable()
    clij2.statisticsOfBackgroundAndLabelledPixels(gfx4, gfx5, results)

    for i in range(results.size()):
        table.incrementCounter()
        table.addValue("Frame (Time)", nFrame)
        table.addValue("Label", i)
        table.addValue("MEAN_INTENSITY", results.getValue("MEAN_INTENSITY", i))
        table.addValue("SUM_INTENSITY", results.getValue("SUM_INTENSITY", i))
        table.addValue("MINIMUM_INTENSITY",
                       results.getValue("MINIMUM_INTENSITY", i))
        table.addValue("MAXIMUM_INTENSITY",
                       results.getValue("MAXIMUM_INTENSITY", i))
        table.addValue("STANDARD_DEVIATION_INTENSITY",
                       results.getValue("STANDARD_DEVIATION_INTENSITY", i))
        table.addValue("PIXEL_COUNT", results.getValue("PIXEL_COUNT", i))
        table.addValue("CENTROID_X", results.getValue("CENTROID_X", i))
        table.addValue("CENTROID_Y", results.getValue("CENTROID_Y", i))
        table.addValue("CENTROID_Z", results.getValue("CENTROID_Z", i))

        table.addValue("File name", originalTitle)

    return table
Exemplo n.º 29
0
def ana_particles(imp, minSize, maxSize, minCirc, bHeadless=True):
    """ana_particles(imp, minSize, maxSize, minCirc, bHeadless=True)
	Analyze particles using a watershed separation. If headless=True, we cannot
	redirect the intensity measurement to the original image because it is never
	displayed. If we display the original, we can and get the mean gray level. We
	may then compute the particle contrast from the measured Izero value for the image.
	No ability here to draw outlines on the original.
	"""
    strName = imp.getShortTitle()
    imp.setTitle("original")
    ret = imp.duplicate()
    ret.setTitle("work")
    IJ.run(ret, "Enhance Contrast", "saturated=0.35")
    IJ.run(ret, "8-bit", "")
    IJ.run(ret, "Threshold", "method=Default white")
    IJ.run(ret, "Watershed", "")
    rt = ResultsTable()
    # strSetMeas = "area mean modal min center perimeter bounding fit shape feret's redirect='original' decimal=3"
    # N.B. redirect will not work without a displayed image, so we cannot use a gray level image
    if bHeadless == True:
        strSetMeas = "area mean modal min center perimeter bounding fit shape feret's decimal=3"
    else:
        imp.show()
        strSetMeas = "area mean modal min center perimeter bounding fit shape feret's redirect='original' decimal=3"

    IJ.run("Set Measurements...", strSetMeas)
    # note this does not get passed directly to ParticleAnalyzer, so
    # I did this, saved everything and looked for the measurement value in ~/Library/Preferences/IJ_Prefs.txt
    # measurements=27355
    # meas = Measurements.AREA + Measurements.CIRCULARITY + Measurements.PERIMETER + Measurements.SHAPE_DESCRIPTORS
    # didn't work reliably
    meas = 27355
    pa = ParticleAnalyzer(0, meas, rt, minSize, maxSize, minCirc, 1.0)
    pa.analyze(ret)
    rt.createTableFromImage(ret.getProcessor())
    return [ret, rt]
Exemplo n.º 30
0
def analyze_homogeneity(image_title):
    IJ.selectWindow(image_title)
    raw_imp = IJ.getImage()
    IJ.run(raw_imp, "Duplicate...", "title=Homogeneity duplicate")
    IJ.selectWindow('Homogeneity')
    hg_imp = IJ.getImage()

    # Get a 2D image
    if hg_imp.getNSlices() > 1:
        IJ.run(hg_imp, "Z Project...", "projection=[Average Intensity]")
        hg_imp.close()
        IJ.selectWindow('MAX_Homogeneity')
        hg_imp = IJ.getImage()
        hg_imp.setTitle('Homogeneity')

    # Blur and BG correct the image
    IJ.run(hg_imp, 'Gaussian Blur...', 'sigma=' + str(HOMOGENEITY_RADIUS) + ' stack')

    # Detect the spots
    IJ.setAutoThreshold(hg_imp, HOMOGENEITY_THRESHOLD + " dark")
    rm = RoiManager(True)
    table = ResultsTable()
    pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER,
                          ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES,
                          Measurements.AREA, # measurements
                          table, # Output table
                          0, # MinSize
                          500, # MaxSize
                          0.0, # minCirc
                          1.0) # maxCirc
    pa.setHideOutputImage(True)
    pa.analyze(hg_imp)

    areas = table.getColumn(table.getHeadings().index('Area'))

    median_areas = compute_median(areas)
    st_dev_areas = compute_std_dev(areas, median_areas)
    thresholds_areas = (median_areas - (2 * st_dev_areas), median_areas + (2 * st_dev_areas))

    roi_measurements = {'integrated_density': [],
                        'max': [],
                        'area': []}
    IJ.setForegroundColor(0, 0, 0)
    for roi in rm.getRoisAsArray():
        hg_imp.setRoi(roi)
        if REMOVE_CROSS and hg_imp.getStatistics().AREA > thresholds_areas[1]:
            rm.runCommand('Fill')
        else:
            roi_measurements['integrated_density'].append(hg_imp.getStatistics().INTEGRATED_DENSITY)
            roi_measurements['max'].append(hg_imp.getStatistics().MIN_MAX)
            roi_measurements['integrated_densities'].append(hg_imp.getStatistics().AREA)

        rm.runCommand('Delete')

    measuremnts = {'mean_integrated_density': compute_mean(roi_measurements['integrated_density']),
                   'median_integrated_density': compute_median(roi_measurements['integrated_density']),
                   'std_dev_integrated_density': compute_std_dev(roi_measurements['integrated_density']),
                   'mean_max': compute_mean(roi_measurements['max']),
                   'median_max': compute_median(roi_measurements['max']),
                   'std_dev_max': compute_std_dev(roi_measurements['max']),
                   'mean_area': compute_mean(roi_measurements['max']),
                   'median_area': compute_median(roi_measurements['max']),
                   'std_dev_area': compute_std_dev(roi_measurements['max']),
                   }

    # generate homogeinity image
    # calculate interpoint distance in pixels
    nr_point_columns = int(sqrt(len(measuremnts['mean_max'])))
    # TODO: This is a rough estimation that does not take into account margins or rectangular FOVs
    inter_point_dist = hg_imp.getWidth() / nr_point_columns
    IJ.run(hg_imp, "Maximum...", "radius="+(inter_point_dist*1.22))
    # Normalize to 100
    IJ.run(hg_imp, "Divide...", "value=" + max(roi_measurements['max'] / 100))
    IJ.run(hg_imp, "Gaussian Blur...", "sigma=" + (inter_point_dist/2))
    hg_imp.getProcessor.setMinAndMax(0, 255)

    # Create a LUT based on a predefined threshold
    red = zeros(256, 'b')
    green = zeros(256, 'b')
    blue = zeros(256, 'b')
    acceptance_threshold = HOMOGENEITY_ACCEPTANCE_THRESHOLD * 256 / 100
    for i in range(256):
        red[i] = (i - acceptance_threshold)
        green[i] = (i)
    homogeneity_LUT = LUT(red, green, blue)
    hg_imp.setLut(homogeneity_LUT)

    return hg_imp, measuremnts