Exemplo n.º 1
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)
Exemplo n.º 2
0
def geometrical_measure_3D(imp_label):
  # remove results table if exists:
  close_non_image_window("Results")
  # measure
  #imp_label.show()
  rt = ResultsTable.getResultsTable()
  IJ.run(imp_label, "3D Geometrical Measure", "");
  rt = ResultsTable.getResultsTable()
  return rt
Exemplo n.º 3
0
def geometrical_measure_3D(imp_label):
  # remove results table if exists:
  close_non_image_window("Results")
  # measure
  #imp_label.show()
  rt = ResultsTable.getResultsTable()
  IJ.run(imp_label, "3D Geometrical Measure", "");
  rt = ResultsTable.getResultsTable()
  return rt
Exemplo n.º 4
0
def measure_roi_set(roi_set, imp, set_measure=MEAS_ALL) :
    """requires imp because it won't measure without one
    note.. side effects: ResultsTable and RoiManager cleared"""
    # imp.show()
    rt = ResultsTable.getResultsTable()
    rt.reset()

    rm = RoiManager.getRoiManager()
    rm.reset()


    if roi_set is not None :

        for roi in roi_set :
            add_roi(roi)

    rm.setSelectedIndexes([x for x in range(rm.getCount())])
    setMeasurementInt(set_measure)
    print("before rm measure")
    # IJ.setActiveImage(imp)
    # IJ.selectWindow(imp.getTitle())
    # imp.show()
    try :
    # input()
    # for roi in roi_set :
        # imp.
        rm.runCommand(imp, "Measure")
    except :
        input()
    print("after rm measure")

    results = rt_to_col_dict()
    # imp.hide()
    return results
def measure_growth(imgDir, filename = "Fiji_Growth.txt"):
    """ Collects measurement data in pixels and writes to a file. Uses straightened binary images"""
    f = open(imgDir + filename, 'w')
    f.write("Img number\tEnd point (pixels)\n")
    IJ.run("Set Measurements...", "area mean min center redirect=None decimal=3")
    index = "000000000"
    filename = imgDir + "/binary" + "/img_" + index + "__000-padded.tif"
    while path.exists(filename):
		imp = IJ.openImage(filename)
		imp.show()
		IJ.run("Clear Results")
		for i in xrange(800): #hard coded to target length for now
			IJ.makeRectangle(i, 0, 1, 80)
			IJ.run("Measure")
			table = RT.getResultsTable()
			#print "i:", i, "counter:", table.getCounter()
			maxi = RT.getValue(table, "Max", i)
			if maxi == 0:
				f.write(str(int(index)) + "\t" + str(i) + "\n")
				break

		IJ.runMacro("while (nImages>0) {selectImage(nImages);close();}")
		index = to_9_Digits(str(int(index)+1))
		filename = imgDir + "/padded" + "/img_" + index + "__000-padded.tif"
    f.close()
Exemplo n.º 6
0
 def roiAnalysisToWrite(self, roiTableName):
     #I can't figure out the syntax to preallocate memory,
     #this will not scale to many speckles
     try:
         RT = ResultsTable.getResultsTable(roiTableName)
         headings = RT.getHeadings()
         labelCol = RT.getColumnAsVariables(headings[0])
         headers = headings[1:]
         numCols = len(headers)
         numRows = len(labelCol)
         out = []
         for col in range(numCols):
             out.append([])
             column = RT.getColumnAsVariables(headers[col])
             for row in range(numRows):
                 out[col].append(column[row].getValue())
         outT = []
         for i in range(numRows):
             lis = []
             lis.append(labelCol[i].getString())
             for j in range(numCols):
                 lis.append(out[j][i])
             outT.append(lis)
         return outT
     except:
         print("failed roi read")
         return []
Exemplo n.º 7
0
	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()
Exemplo n.º 8
0
def make_nucs(hseg):
    """given an hseg, assumed to have a nuc_bin_imp, creates the nuc"""
    rm = RoiManager.getRoiManager()
    rm.reset()

    if UPDATE1:
        IJ.run(hseg.nuc_bin_imp, "Invert", "")

    rt = ResultsTable.getResultsTable()
    rt.reset()
    IJ.run(hseg.nuc_bin_imp, "Analyze Particles...", "add")

    rois = rm.getRoisAsArray()
    problem_nucs = []
    for roi in rois:
        nuc_cent = roi_cent(roi, integer=True)

        found_cell = False
        for cell in hseg.cells.values():
            if cell.roi.contains(*nuc_cent):
                cell.add_nuc(roi)
                found_cell = True
                break

        if not found_cell:
            IJ.log('Nuc not in any cell for hemisegment {}'.format(hseg.name))
            problem_nucs.append(roi)

    return problem_nucs
def delete(imp, roiMan, roiTotal):

	# set results table
	rt = ResultsTable.getResultsTable()
	# set up analyzer
	analyzer = Analyzer(imp, 1, rt)
	totalPixels = 0
	# Set the color and line options for erasing
	IJ.run("Colors...", "foreground=black background=black selection=magenta")

	if roiMan is not None:
		# Iterate through the ROIs
		for roi in xrange(roiTotal):
			# Select the ROI
			roiMan.select(roi)
			selectRoi = roiMan.getRoi(roi)
			# measure
			analyzer.measure()
			meas = rt.getRowAsString(0)
			newLine = meas.split("	", 1)
			pixels = float(newLine[1])
			totalPixels = totalPixels + pixels
			# Tag the ROI
			IJ.run(imp, "Fill", "slice")
		# end for loop
		return totalPixels
	else:
		return 0
Exemplo n.º 10
0
def relabel():
    import re
    from ij.measure import ResultsTable
    rt = ResultsTable.getResultsTable()
    nResults = rt.size()
    for result in range(nResults):
        oldLabel = rt.getLabel(result)
        delimiters = []
        keywords = ["series"]
        for keyword in keywords:
            if keyword in oldLabel:
                delimiters.append(oldLabel.index(keyword))

        channel = oldLabel[0:2]
        try:
            series = "FOV" + oldLabel[(delimiters[0] + 7):(delimiters[0] + 9)]
        except IndexError:
            series = "FOV?"

        foundColons = [m.start() for m in re.finditer(':', oldLabel)]
        cell = oldLabel[foundColons[0] + 1:foundColons[1]]

        newLabel = channel + "_" + series + "_" + cell
        rt.setLabel(newLabel, result)
    rt.show("Results")
 def containsRoot_(self):
     IJ.run("Clear Results")
     IJ.run("Measure")
     table = RT.getResultsTable()
     if RT.getValue(table, "Max", 0) == 0:
         return False
     return True
Exemplo n.º 12
0
    def create_nucs(self) :
        """ """
        for cell in self.cells() :
            cell._nucs = []

        rm = RoiManager.getRoiManager()
        rm.reset()

        IJ.run(self.nuc_bin(), "Invert", "")


        rt = ResultsTable.getResultsTable()
        rt.reset()
        IJ.run(self.nuc_bin(), "Analyze Particles...", "add")

        rois = rm.getRoisAsArray()
        IJ.run(self.nuc_bin(),"Remove Overlay", "");



        problem_nucs = []
        for roi in rois :
            nuc_cent = futils.roi_cent(roi, integer=True)

            found_cell = False
            for cell in self.cells() :
                if cell.roi().contains(*nuc_cent) :
                    cell.add_nuc(roi)
                    found_cell = True
                    break

            if not found_cell :
                self.exper.log('Nuc not in any cell for hemisegment {}'.format(self.name))
                problem_nucs.append(roi)
        return problem_nucs
def run_straighten(roiWindowsize=4):
    """ Original straightening function based on Nick's macro. Used in final version.
    Returns coordinate string used to make centerline. """
    IJ.run("Set Measurements...", "mean min center redirect=None decimal=3")
    IJ.runMacro("//setTool(\"freeline\");")
    IJ.run("Line Width...", "line=80")
    numPoints = 512 / roiWindowsize
    xvals = []
    yvals = []
    maxvals = []
    counter = 0

    for i in range(0, 512, roiWindowsize):
        IJ.run("Clear Results")
        IJ.makeRectangle(i, 0, roiWindowsize, 512)
        IJ.run("Measure")
        table = RT.getResultsTable()
        xvals.append(i + roiWindowsize / 2)
        yvals.append(RT.getValue(table, "YM", 0))
        maxvals.append((RT.getValue(table, "Max", 0)))

        if maxvals[counter] == 0 and counter > 0:
            yvals[counter] = yvals[counter - 1]

        counter += 1

    coords = ""
    for i in range(numPoints - 1):
        coords += str(xvals[i]) + ", " + str(yvals[i]) + ", "
    coords += str(xvals[numPoints - 1]) + ", " + str(yvals[numPoints - 1])

    IJ.runMacro("makeLine(" + coords + ")")
    IJ.run("Straighten...", "line = 80")
    return coords
def measure_growth(imgDir, filename="Fiji_Growth.txt"):
    """ Collects measurement data in pixels and writes to a file. Uses straightened binary images"""
    f = open(imgDir + filename, 'w')
    f.write("Img number\tEnd point (pixels)\n")
    IJ.run("Set Measurements...",
           "area mean min center redirect=None decimal=3")
    index = "000000000"
    filename = imgDir + "/binary" + "/img_" + index + "__000-padded.tif"
    while path.exists(filename):
        imp = IJ.openImage(filename)
        imp.show()
        IJ.run("Clear Results")
        for i in xrange(800):  #hard coded to target length for now
            IJ.makeRectangle(i, 0, 1, 80)
            IJ.run("Measure")
            table = RT.getResultsTable()
            #print "i:", i, "counter:", table.getCounter()
            maxi = RT.getValue(table, "Max", i)
            if maxi == 0:
                f.write(str(int(index)) + "\t" + str(i) + "\n")
                break

        IJ.runMacro("while (nImages>0) {selectImage(nImages);close();}")
        index = to_9_Digits(str(int(index) + 1))
        filename = imgDir + "/padded" + "/img_" + index + "__000-padded.tif"
    f.close()
def getColumnIndex(column):
    rt = ResultsTable.getResultsTable()
    headings = rt.getHeadings()
    for i, heading in enumerate(headings, start=1):
        if heading == column:
            return i
    return None
def nuclei_processor(imp_particles, thresh_type, folder, impname,
                     channel_name):
    rm = RoiManager.getInstance()
    if not rm:
        rm = RoiManager()
    rm.reset()

    # define a results table
    rt = ResultsTable.getResultsTable()

    imp_particles.show()
    # generate thresholded image for ROI
    nuclei = imp_particles.duplicate()
    nuclei.show()
    IJ.run("Gaussian Blur...", "sigma=3")
    IJ.setAutoThreshold(nuclei, thresh_type)
    IJ.run("Convert to Mask")
    IJ.run("Fill Holes")
    #	IJ.run("Watershed")

    # select thresholded image (to set ROIs)
    IJ.run(
        "Set Measurements...",
        "area mean standard min area_fraction limit display add redirect=[" +
        imp_particles.title + "] decimal=3")
    IJ.run("Analyze Particles...",
           "size=30-Infinity show=Outlines display clear add")

    # get the ROI manager and save
    rm.runCommand(
        "save selected",
        os.path.join(folder, impname + '_' + channel_name + "_ROIs.zip"))
Exemplo n.º 17
0
def main():
    features = ["Area"]
    numberOfClusters = 2

    features, numberOfClusters = getArguments(features, numberOfClusters)

    rt = RT.getResultsTable()
    if (rt.size() < 2):
        exit("No data found")

    attributes = featuresToAttributes(features)
    data = readDataFromResultsTable(attributes, rt)

    clusterer = createClusterer(numberOfClusters)
    clusterer.buildClusterer(data)
    (mu1, sig1, mu2, sig2, prior1,
     prior2) = getClusterInformationFrom(clusterer)
    threshold = intersection(mu2, sig2, mu1, sig1)

    print(clusterer.toString())
    print "intersection at: ", threshold

    if (mu1 > mu2):
        mu1, sig1, mu2, sig2, prior1, prior2 = mu2, sig2, mu1, sig1, prior2, prior1

    writeToTable(mu1, sig1, prior1, mu2, sig2, prior2, threshold)
def linkSpots():
	rt = ResultsTable.getResultsTable()
	X = rt.getColumn(ResultsTable.X_CENTROID)
	Y = rt.getColumn(ResultsTable.Y_CENTROID)
	D = rt.getColumn(ResultsTable.FERET)
	SLICE = rt.getColumn(ResultsTable.SLICE)
	spotsByScale = getRoisBySlice(SLICE)
	print(spotsByScale)
	## set objects of spots i scale 1 to the id of the spot
	spots = spotsByScale[1]
	for spot in spots:
		spot['object']=spot['id']
	for s in range(2, len(spotsByScale)+1):
		spots = spotsByScale[s]
		for spot in spots:
			spot['object']=spot['id']						# initially set the object to which the spot belong to the spot id
			spotsLastScale = spotsByScale[s-1]
			minDist = float("inf")
			minObject = None
			for spotLastScale in spotsLastScale:
			# for each spot on the next scale
				deltaX = X[spotLastScale['id']]-X[spot['id']]
				deltaY = Y[spotLastScale['id']]-Y[spot['id']]
				dist = math.sqrt((deltaX * deltaX) + (deltaY*deltaY))
				print("spot", spot['id'], "spot s-1", spotLastScale['id'], dist)   
				if (dist<(D[spot['id']])/2.0):
					if (dist<minDist):
						minDist = dist
						minObject = spotLastScale['object']
						print('hit', minDist, minObject)
			if minObject is not None:
				spot['object'] = minObject	
				print("minObject", minObject)
	return spotsByScale 
 def containsRoot_(self):
     IJ.run("Clear Results")
     IJ.run("Measure")
     table = RT.getResultsTable()
     if RT.getValue(table, "Max", 0) == 0:
         return False
     return True
def run_straighten(roiWindowsize = 4):
    """ Original straightening function based on Nick's macro. Used in final version.
    Returns coordinate string used to make centerline. """
    IJ.run("Set Measurements...", "mean min center redirect=None decimal=3")
    IJ.runMacro("//setTool(\"freeline\");")
    IJ.run("Line Width...", "line=80");
    numPoints = 512/roiWindowsize
    xvals = []
    yvals = []
    maxvals = []
    counter = 0

    for i in range(0, 512, roiWindowsize):
        IJ.run("Clear Results")
        IJ.makeRectangle(i, 0, roiWindowsize, 512)
        IJ.run("Measure")
        table = RT.getResultsTable()
        xvals.append(i + roiWindowsize/2)
        yvals.append(RT.getValue(table, "YM", 0))
        maxvals.append((RT.getValue(table, "Max", 0)))

        if maxvals[counter] == 0 and counter > 0:
            yvals[counter] = yvals[counter - 1]

        counter += 1

    coords = ""
    for i in range(numPoints - 1):
        coords += str(xvals[i]) + ", " + str(yvals[i]) +", "
    coords += str(xvals[numPoints-1]) + ", " + str(yvals[numPoints-1])

    IJ.runMacro("makeLine("+coords+")")
    IJ.run("Straighten...", "line = 80")
    return coords
Exemplo n.º 21
0
def intensity_measure_3D(imp_intens, imp_label):
  imp_intens.show()
  imp_label.show()
  IJ.run(imp_intens, "3D Intensity Measure", "objects=[%s] signal=[%s]" % (imp_label.getTitle(), imp_intens.getTitle()) );
  imp_intens.hide()
  imp_label.hide()
  rt = ResultsTable.getResultsTable()
  return rt
Exemplo n.º 22
0
def intensity_measure_3D(imp_intens, imp_label):
  imp_intens.show()
  imp_label.show()
  IJ.run(imp_intens, "3D Intensity Measure", "objects=[%s] signal=[%s]" % (imp_label.getTitle(), imp_intens.getTitle()) );
  imp_intens.hide()
  imp_label.hide()
  rt = ResultsTable.getResultsTable()
  return rt
Exemplo n.º 23
0
def run_comdet(image):
    IJ.run(
        image, "Detect Particles",
        " two=[Detect in both channels independently] ch1a=" + str(ch1size) +
        " ch1s=" + str(ch1thresh) + " ch2a=" + str(ch2size) + " ch2s=" +
        str(ch2thresh) + " calculate max=" + str(coloc) + " add=Nothing")
    rt = ResultsTable.getResultsTable()
    return rt
Exemplo n.º 24
0
def analyzeImage(passImage, passModel, passChannel, passProbability,
                 passPixels, passOutput):
    retResults = list()
    windows = set()

    # Register current window
    registerWindow(passImage.title, windows)

    # Extract the requested channel
    IJ.run("Z Project...", "projection=[Max Intensity]")
    registerWindow("MAX_" + passImage.title, windows)
    IJ.run("Duplicate...", "title=temp")
    registerWindow("temp", windows)

    # Apply WEKA training model to image
    wekaSeg = WekaSegmentation(WindowManager.getCurrentImage())
    wekaSeg.loadClassifier(passModel)
    wekaSeg.applyClassifier(True)

    # Extract first slice of probability map
    wekaImg = wekaSeg.getClassifiedImage()
    wekaImg.show()
    registerWindow("Probability maps", windows)
    IJ.setSlice(1)
    IJ.run("Duplicate...", "title=temp2")
    registerWindow("temp2", windows)

    # Apply threshold and save
    IJ.setThreshold(passProbability, 1, "Black & White")
    fileParts = passImage.getTitle().split(".")
    IJ.save(
        os.path.join(
            passOutput, "{0}-probmap.png".format(fileParts[0],
                                                 '.'.join(fileParts[1:]))))

    # Perform particle analysis and save
    IJ.run("Analyze Particles...",
           "size={0}-Infinity show=Outlines pixel clear".format(passPixels))
    registerWindow("Drawing of temp2", windows)
    IJ.save(
        os.path.join(
            passOutput, "{0}-particles.png".format(fileParts[0],
                                                   '.'.join(fileParts[1:]))))

    # Get measurements
    tableResults = ResultsTable.getResultsTable()
    for rowIdx in range(tableResults.size()):
        retResults.append(tableResults.getRowAsString(rowIdx).split())
        retResults[-1].insert(
            0,
            WindowManager.getCurrentImage().getCalibration().unit)
        retResults[-1].append(
            float(retResults[-1][4]) / float(retResults[-1][3]))

    # Close windows
    closeWindows(windows)

    return retResults
Exemplo n.º 25
0
def auto_resize_angle_measure(img, two_sarcomere_size):
    """Resizes and measures angle of offset for img based on T-tubules."""
    # Run Fast Fourier Transform on Image to get Power Spectral Density
    IJ.run(img, "FFT", "")

    # Select PSD image.
    fft_title = "FFT of " + img.getTitle()
    fft_img = WindowManager.getImage(fft_title)

    # Threshold the image and create binary mask.
    IJ.setThreshold(151, 255)
    #IJ.setThreshold(135, 255)
    IJ.run(fft_img, "Convert to Mask", "")

    # Set measurements for fitting an ellipse and fit them to data.
    IJ.run(fft_img, "Set Measurements...",
           "area centroid fit redirect=None decimal=2")
    if dev_options:
        args = "size=10-Infinity show=Ellipses display"
    else:
        args = "size=10-Inifinity"
    IJ.run(fft_img, "Analyze Particles...", args)
    results = ResultsTable.getResultsTable()
    angle_column = results.getColumnIndex("Angle")
    area_column = results.getColumnIndex("Area")
    centroid_x_column = results.getColumnIndex("X")
    centroid_y_column = results.getColumnIndex("Y")
    # Sort by area since we need the largest two ellipses.
    results.sort("Area")
    # Grab info for the largest two ellipses.
    areas = results.getColumnAsDoubles(area_column)
    angles = results.getColumnAsDoubles(angle_column)
    c_xs = results.getColumnAsDoubles(centroid_x_column)
    c_ys = results.getColumnAsDoubles(centroid_y_column)

    # Calculate offset angle from main ellipse.
    rotation_angle = angles[-1] - 90.

    # Measure distance between centroids of two largest ellipses using distance measurement tool to get spatial frequency of T-tubules.
    # Note: This needs to be in pixels since the filter size is in pixels.
    c_x_0 = c_xs[-1]
    c_y_0 = c_ys[-1]
    c_x_1 = c_xs[-2]
    c_y_1 = c_ys[-2]
    dist_gap = ((c_x_0 - c_x_1)**2 + (c_y_0 - c_y_1)**2)**0.5
    old_two_sarcomere_size = 2 * fft_img.getDimensions()[0] / dist_gap

    # Resize based on measured two sarcomere size
    resize_ratio = float(two_sarcomere_size) / float(old_two_sarcomere_size)
    old_width = img.width
    old_height = img.height
    new_width = resize_ratio * old_width
    new_height = resize_ratio * old_height
    resize_args = "width={} height={} depth=1 constrain average interpolation=Bicubic".format(
        new_width, new_height)
    IJ.run(img, "Size...", resize_args)

    return rotation_angle
def straighten_roi_rotation(roiWindowsize = 8):
    """ Root straightening function that rotates ROI to follow root slope.
    Does not work properly.
    """
    IJ.run("Set Measurements...", "mean standard min center redirect=None decimal=3")
    IJ.runMacro("//setTool(\"freeline\");")
    IJ.run("Line Width...", "line=80");
    #numPoints = 512/roiWindowsize
    xvals = []
    yvals = []
    maxvals = []
    counter = 0
    maxIters = 800/roiWindowsize
    minIters = 10

    imp = IJ.getImage().getProcessor()

    rm = RoiManager()
    if find_first_pixel(0,imp) == None or find_last_pixel(0,imp)[1] == None:
        return
    y = (find_first_pixel(0,imp)[1]+find_last_pixel(0,imp)[1])/2
    roi = roiWindow_(imp, center = (roiWindowsize/2,y), width = roiWindowsize, height = 512)
    xvals.append(roiWindowsize/2)
    yvals.append(y)
    maxvals.append(0)
    roi.findTilt_()
    i = 0
    while i < maxIters and roi.containsRoot_():
    	roi.advance_(roiWindowsize)
        IJ.run("Clear Results")
        IJ.run("Measure")
        table = RT.getResultsTable()

        x  = RT.getValue(table, "XM", 0)
        y = RT.getValue(table, "YM", 0)
        if imp.getPixel(int(x),int(y)) != 0:
            xvals.append(x)
            yvals.append(y)
            maxvals.append((RT.getValue(table, "Max", 0)))


        #roi.advance_(roiWindowsize)
        print "here"
        roi.unrotateRoot_()
        IJ.run("Clear Results")
        IJ.run("Measure")
        roi.restoreCenter_(RT.getValue(table, "XM", 0), RT.getValue(table, "YM", 0))
        #exit(1)
        sleep(.5)
        roi.findTilt_()
        i += 1
    coords = ""
    for i in range(len(xvals)-1):
        coords += str(xvals[i]) + ", " + str(yvals[i]) +", "
    coords += str(xvals[len(xvals)-1]) + ", " + str(yvals[len(xvals)-1])

    IJ.runMacro("makeLine("+coords+")")
    IJ.run("Straighten...", "line = 80")
def getColumn(aC):
    rt = ResultsTable.getResultsTable()
    anIndex = getColumnIndex(aC)
    column = []
    for i in range(0, rt.size()):
        columns = rt.getRowAsString(i).split('\t')
        v = float(columns[anIndex])
        column.append(v)
    return column
Exemplo n.º 28
0
    def filterPaths(self):
        evaluationTableTitle = "PathEvaluationTest"
        pathTableTitle = "pathsTable"
        evaluationTable = ResultsTable.getResultsTable(evaluationTableTitle)
        pathTable = ResultsTable.getResultsTable(pathTableTitle)
        rowToDelete = [
            index for index, p in enumerate(self.paths, start=0)
            if not p.isWanted(evaluationTable, index)
        ]

        for index in rowToDelete[::-1]:
            pathTable.deleteRow(index)
            evaluationTable.deleteRow(index)
            self.paths.pop(index)

        evaluationTable.show(evaluationTableTitle)
        pathTable.show(pathTableTitle)
        self.addPathsToRoiManager(evaluationTable)
Exemplo n.º 29
0
def f3_clic_saveTable(event):
   print "Click Save Table"
   RM = RoiManager()        # we create an instance of the RoiManager class
   rm = RM.getRoiManager()
   imp = gvars["workingImage"]
   table_message = []
   is_scaled = imp.getCalibration().scaled()
   if not is_scaled:
      JOptionPane.showMessageDialog(None, "Warning: your image is not spatially calibrated. \nTo calibrate, go to Analyze > Set Scale...")

   nChannels = imp.getNChannels()

   print "Total channels:"
   print nChannels
   for current_channel in range(1,nChannels+1):
      print "Current channel:"
      print current_channel

      imp.setSlice(current_channel)
      current_slice = str(imp.getCurrentSlice()) #Get current slice for saving into filename
      print "Current slice:"
      print current_slice

      is_scaled = imp.getCalibration().scaled()
      if is_scaled:
          spatial_cal = "True"
      else:
          spatial_cal = "False"

      IJ.run("Clear Results", "")
      rm.runCommand(imp,"Select All");
      rm.runCommand(imp,"Measure")

      table = ResultsTable.getResultsTable().clone()
      IJ.selectWindow("Results")
      IJ.run("Close")

      filename = os.path.split(gvars["path_original_image"])[1]
      print filename

      pixels = gvars['eroded_pixels'] #To save number of eroded pixels in table and table name

      for i in range(0, table.size()):
         table.setValue('File', i, str(filename))
         table.setValue('Channel', i, current_channel)
         table.setValue('Pixels_eroded', i, str(pixels))
         table.setValue('Spatial_calibration', i, spatial_cal)

      table.show("Tabla actualizada")


      path_to_table = str(gvars['path_original_image'].replace(".tif", "") + "_Erosion_" +str(pixels)+ "px_Channel_" + str(current_channel) + ".csv")
      IJ.saveAs("Results", path_to_table)
      table_message.append("Table saved to %s" % path_to_table)

   JOptionPane.showMessageDialog(None, "\n".join(table_message))
def measureSkeletonTotalLength(imp, root):
  IJ.run(imp,"Analyze Skeleton (2D/3D)", "prune=none")
  totalLength = 0
  nBranches = 0
  rt = ResultsTable.getResultsTable()
  avgLengths = rt.getColumn(rt.getColumnIndex("Average Branch Length"))
  for i in range(len(avgLengths)):
    totalLength = totalLength + rt.getValue("# Branches", i) * rt.getValue("Average Branch Length", i)
    nBranches = nBranches + rt.getValue("# Branches", i)	
  print root,",",imp.getTitle(),",",totalLength,",",nBranches
Exemplo n.º 31
0
def measureSkeletonTotalLength(imp):
  IJ.run(imp,"Analyze Skeleton (2D/3D)", "prune=none")
  totalLength = 0
  nBranches = 0
  rt = ResultsTable.getResultsTable()
  avgLengths = rt.getColumn(rt.getColumnIndex("Average Branch Length"))
  for i in range(len(avgLengths)):
    totalLength = totalLength + rt.getValue("# Branches", i) * rt.getValue("Average Branch Length", i)
    nBranches = nBranches + rt.getValue("# Branches", i)	
  print root,",",imp.getTitle(),",",totalLength,",",nBranches
def drawMinima(minima):
	rt = ResultsTable.getResultsTable()
	X = rt.getColumn(ResultsTable.X_CENTROID)
	Y = rt.getColumn(ResultsTable.Y_CENTROID)
	D = rt.getColumn(ResultsTable.FERET)	
	overlay = Overlay()
	for minimum in minima:
		index = minima[minimum]
	 	r = float(D[index]) / 2
		roi = OvalRoi(float(X[index])-r, float(Y[index])-r, float(D[index]), float(D[index]))	
		overlay.add(roi)
	IJ.getImage().setOverlay(overlay)
def main(minOverlap):
    rt = ResultsTable.getResultsTable()
    X = rt.getColumn(ResultsTable.X_CENTROID)
    Y = rt.getColumn(ResultsTable.Y_CENTROID)
    D = rt.getColumn(ResultsTable.FERET)
    width = len(X)
    height = width - 1

    matrix = createGraph(X, Y, D, minOverlap)
    graph = matrix_to_list(matrix)
    components = findConnectedComponents(graph)
    mergeRois(components)
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)
def learn(imp):

    IJ.run(imp, "Line Width...", "line=10")
    IJ.run("Colors...", "foreground=black background=black selection=red")

    # Clear ROI manager
    roiMan = RoiManager.getInstance()
    if roiMan is not None:
        roiMan.reset()

    # set results table
    rt = ResultsTable.getResultsTable()
    # set up analyzer
    analyzer = Analyzer(imp, 1, rt)

    impBrightness = ProcessHSB.getBrightness(imp)
    IJ.run(impBrightness, "8-bit", "")
    IJ.run(impBrightness, "Auto Threshold", "method=Shanbhag white")
    IJ.run(impBrightness, "Analyze Particles...",
           "size=50000-Infinity circularity=0.00-1.00 show=Masks add in_situ")

    # Pixel running total
    pixelTotal = zeros('f', 4)

    roiTotal = roiMan.getCount()

    if roiMan is not None:

        # Iterate throught the ROIs
        for roi in xrange(roiTotal):
            roiMan.select(roi)
            selectRoi = roiMan.getRoi(roi)

            option = getOptions()

            # measure
            analyzer.measure()
            meas = rt.getRowAsString(0)
            newLine = meas.split("	", 1)
            pixels = float(newLine[1])
            # Tag the ROI
            IJ.run(imp, "Fill", "slice")

            pixelTotal[0] = pixelTotal[0] + (option[0] * pixels)
            pixelTotal[1] = pixelTotal[1] + (option[1] * pixels)
            pixelTotal[2] = pixelTotal[2] + (option[2] * pixels)
            pixelTotal[3] = pixelTotal[3] + (option[3] * pixels)

        return pixelTotal
    else:
        return pixelTotal
Exemplo n.º 36
0
def rt_to_col_dict() :
    """takes the ResultsTable and return its contents as an col_dict(dictionary whose keys are heads of columns and values are the columns)"""
    # print("rt_to_col_dict")

    rt = ResultsTable.getResultsTable()

    # print(headings)



    col_dict = {}


    col_dict["Label"] = []

    for n in range(rt.size()) :
        col_dict['Label'].append(rt.getLabel(n))



    headings = rt.getHeadings()



    for heading in headings :
        if heading == "Label" :
            continue
        col_ind = rt.getColumnIndex(heading)
        # print(col_ind)
        # print(heading)
        col = rt.getColumn(col_ind)
        col_dict[heading] = col

    #
    # for i in range(len(headings)) :
    #     temp = rt.getColumn(i)
    #     # t = temp is not None
    #     print("{}. {} = {}".format(i, headings[i], temp is not None))
    #
    #     if temp is not None :
    #         col_dict[rt.getColumnHeading(i)] = list(temp)
    #



    col_dict["Label"] = []

    for n in range(rt.size()) :
        col_dict['Label'].append(rt.getLabel(n))

    return col_dict
def analyse(imp, root, filename, thresholds):
  closeAllImageWindows() 
  imp.show()
  print ""
  print(imp.getTitle())
  print "**********************************"

  IJ.run("Set Measurements...", "integrated redirect=None decimal=2");
  # get image calibration info
  IJ.run(imp, "Properties...", "unit=pixel pixel_width=1 pixel_height=1");
  
  # convert to 8-bit
  IJ.setMinAndMax(imp, 0, 65535);
  IJ.run(imp, "8-bit", "");
  thresholds = [(x / 65535 * 255) for x in thresholds]

  # Nuclei
  #closeAllNoneImageWindows()
  iChannel = 1
  imp.setSlice(iChannel)
  IJ.run(imp, "Gaussian Blur...", "sigma=2 slice");
  IJ.setThreshold(imp, thresholds[iChannel-1], 1000000000)
  IJ.run(imp, "Convert to Mask", "method=Default background=Dark only black");
  IJ.run(imp, "Measure", "");
  rt = ResultsTable.getResultsTable()
  values = rt.getColumnAsDoubles(rt.getColumnIndex("RawIntDen"))
  print("Area Nuclei (pixel^2) =",values[-1]/255)
  
  
  # Dots
  #closeAllNoneImageWindows()
  iChannel = 3
  imp.setSlice(iChannel)
  IJ.run(imp, "Gaussian Blur...", "sigma=1 slice");
  IJ.run(imp, "Find Maxima...", "noise="+str(thresholds[iChannel-1])+" output=Count");
  rt = ResultsTable.getResultsTable()
  values = rt.getColumnAsDoubles(rt.getColumnIndex("Count"))
  print("Number of Dots =",values[-1])
Exemplo n.º 38
0
def measureImage(passImage, passPixels, passSteps):
	retResults = list()
	
	# Analyze particles
	IJ.run("Analyze Particles...", "size={0}-Infinity show=Nothing pixel display clear include".format(passPixels));
	
	# Obtain results (initialize if first iteration)
	tableResults = ResultsTable.getResultsTable()
	for rowIdx in range(tableResults.size()):		
		retResults.append(tableResults.getRowAsString(rowIdx).split())

	# Rotate
	IJ.run("Rotate... ", "angle={0} interpolation=Bilinear".format(passSteps))

	return retResults
def getMinima(objects):
	minIndices = {}
	
	rt = ResultsTable.getResultsTable()
	minIntensities = rt.getColumn(ResultsTable.MIN)
	
	for key in objects:
		ids = objects[key]
		minIndex = -1
		minimum = float('inf')
		for anID in ids:
			if minIntensities[anID]<minimum:
				minimum = minIntensities[anID]
				minIndex = anID
		minIndices[key] = minIndex
	return minIndices
Exemplo n.º 40
0
def process(srcDir, currentDir, fileName):
  image = IJ.openImage(os.path.join(currentDir, fileName))
  IJ.run("Clear Results")
  #set lowerbound threshold here
  IJ.setThreshold(image, 200, 10000)

  # Change (1,25) below to (1,n+1) where n is the number of frames
  for slice in range(1,(image.getNSlices()+1),1):
  	image.setSlice(slice)
  	IJ.run(image, "Select All", "")
  	IJ.run(image, "Measure", "")
  
  rt = ResultsTable.getResultsTable()
  # this line calculates the baseline
  baseline = (rt.getValue("IntDen",1) + rt.getValue("IntDen",2) + rt.getValue("IntDen",3))/3.0
  for result in range(0,rt.getCounter()):
  	cur_intensity = rt.getValue("IntDen",result)
  	ratio = cur_intensity/baseline
  	rt.setValue("RawIntDen",result,ratio)

  rt.updateResults()
  image.close()
Exemplo n.º 41
0
def run():
  srcDir = srcFile.getAbsolutePath()
  IJ.run("Set Measurements...", "integrated limit redirect=None decimal=3")
  
  for dirName, subdirs, filenames in os.walk(srcDir):
    if len(subdirs)==0:
      finalResults = []
      for filename in filenames:
        # Check for file extension 
        if not filename.endswith(ext):
          continue
        process(srcDir, dirName, filename)
        rt = ResultsTable.getResultsTable()
        colRaw = rt.getColumnIndex("IntDen")
        colRatio = rt.getColumnIndex("RawIntDen")
        finalResults.append(rt.getColumn(colRaw))
        finalResults.append(rt.getColumn(colRatio))
    
      with open(os.path.join(dirName, dirName+'.csv'), 'wb') as csvfile:
        writer = csv.writer(csvfile, delimiter=",")
        for row in zip(*finalResults):
          writer.writerow(row)
Exemplo n.º 42
0
options = "radius=%d cutoff=%d percentile=%f" % (radius, cutoff, percentile)
thread = thr.currentThread()
original_name = thread.getName()
thread.setName("Run$_my_batch_process")
Macro.setOptions(thr.currentThread(), options)
pt = IJ.runPlugIn(imp, "de.embl.cmci.pt3d.Dot_Detector_3D", "")

impdimA = imp.getDimensions()
ims = imp.createEmptyStack()
for i in range(impdimA[3]): 
	ims.addSlice(None, ByteProcessor(impdimA[0], impdimA[1]))
imp2 = ImagePlus("test", ims)

nSlices = imp2.getNSlices()

rt = ResultsTable.getResultsTable()
xindex = rt.getColumnIndex("x")
yindex = rt.getColumnIndex("y") 
zindex = rt.getColumnIndex("z")
xA = rt.getColumn(xindex)
yA = rt.getColumn(yindex)
zA = rt.getColumn(zindex)

neighbornumA = NeighborChecker(xA, yA, zA, True)

for i in range(len(xA)):
	print xA[i], yA[i], zA[i], " .. Neighbor", neighbornumA[i]   
#	if xA[i] > 0:
	if neighbornumA[i] == 0:	
		cslice=Math.round(zA[i])+1
		if cslice > 0 and cslice <= nSlices:
Exemplo n.º 43
0
def clear_results_table_if_exists():
  rt = ResultsTable.getResultsTable()
  if rt!=None:
    rt.reset()
Exemplo n.º 44
0
# IJ BAR snippet https://github.com/tferr/Scripts/tree/master/Snippets
#
# Calculates the closest pair of points from a 2D/3D list of centroid coordinates (opened in the IJ
# 'Results' table) calling another BAR script to plot the frequencies of nearest neighbor distances.
#
# TF 20150101

import math, sys
from ij import IJ, Menus
import ij.measure.ResultsTable as RT

# Specify column headings listing x,y,z positions
xHeading, yHeading, zHeading = "X", "Y", "Z"

# Retrieve Results Table
rt = RT.getResultsTable()

# Retrive x,y positions
try:
    x = rt.getColumn(rt.getColumnIndex(xHeading))
    y = rt.getColumn(rt.getColumnIndex(yHeading))
except:
    x = y = None

if not None in (x, y):

    # Retrive z positions. Ignore positions if column is not found
    try:
        z = rt.getColumn(rt.getColumnIndex(zHeading))
    except:
        IJ.log("Z-column not found: Assuming 2D distances...")
def run():

    mask_ip = impSkel.getProcessor()
    part_ip = impPart.getProcessor()

    if not mask_ip.isBinary():
        error(impSkel.getTitle() + " is not a binary mask.")
        return

    # Mask grayscale image and skeletonize mask
    try:
        mask_pixels = mask_ip.getPixels()
        part_pixels = part_ip.getPixels()
        for i in xrange(len(part_pixels)):
            if mask_pixels[i] == 0:
                part_pixels[i] = 0
        part_ip.setPixels(part_pixels)
    except IndexError:
        error("Chosen images are not the same size.")
    skeletonize(impSkel)

    # Get skeleton features
    end_points, junctions, junction_voxels, total_len = skeleton_properties(impSkel)
    if not end_points and not junction_voxels:
        error(impSkel.getTitle() + " does not seem a valid skeleton.")
        return

    # Retrieve centroids from IJ1
    threshold_lower = get_threshold(impPart, thres_method)
    cx, cy, n_particles = get_centroids(impPart, threshold_lower)
    if None in (cx, cy):
        error("Verify parameters: No particles detected.")
        return

    # Loop through each centroids and categorize its position
    # according to its distance to skeleton features
    n_bp = n_tip = n_none = n_both = 0

    overlay = cleanse_overlay(impPart.getOverlay())
    for i in range(n_particles):

        j_dist = ep_dist = sys.maxint

        # Retrieve the distance between this particle and the closest junction voxel
        for jvoxel in junction_voxels:
            dist = distance(cx[i], cy[i], jvoxel.x, jvoxel.y)
            if (dist <= cutoff_dist and dist < j_dist):
                j_dist = dist

        # Retrieve the distance between this particle and the closest end-point
        for end_point in end_points:
            dist = distance(cx[i], cy[i], end_point.x, end_point.y)
            if (dist <= cutoff_dist and dist < ep_dist):
                ep_dist = dist

        roi_id = str(i).zfill(len(str(n_particles)))
        roi_name = "Unknown:" + roi_id
        roi_color = Color.ORANGE
        roi_type = 2  # dot

        # Is particle associated with neither junctions nor end-points?
        if j_dist > cutoff_dist and ep_dist > cutoff_dist:
            roi_name = "Unc:" + roi_id
            #n_none += 1
        # Is particle associated with both?
        elif abs(j_dist - ep_dist) <= pixel_size(impPart) / 2:
            roi_name = "J+T:" + roi_id
            roi_color = Color.CYAN
            #roi_type = 1  # crosshair
            n_both += 1
        # Is particle associated with an end-point?
        elif ep_dist < j_dist:
            roi_name = "Tip:" + roi_id
            roi_color = Color.GREEN
            #roi_type = 0  # hybrid
            n_tip += 1
        # Is particle associated with a junction?
        elif ep_dist > j_dist:
            roi_name = "Junction:" + roi_id
            roi_color = Color.MAGENTA
            #roi_type = 3  # circle
            n_bp += 1

        roi = PointRoi(cx[i], cy[i])
        roi.setName(roi_name)
        roi.setStrokeColor(roi_color)
        roi.setPointType(roi_type)
        roi.setSize(2)  # medium
        overlay.add(roi)

    # Display result
    impSkel.setOverlay(overlay)
    impPart.setOverlay(overlay)

    # Output some measurements
    if "table" in output:

        t = ResultsTable.getResultsTable() if "IJ1" in output else DefaultGenericTable()
        addToTable(t, "Part. image", "%s (%s)" % (impPart.getTitle(), impPart.getCalibration().getUnits()))
        addToTable(t, "Skel. image", "%s (%s)" % (impSkel.getTitle(), impSkel.getCalibration().getUnits()))
        addToTable(t, "Junction particles", n_bp)
        addToTable(t, "Tip particles", n_tip)
        addToTable(t, "J+T particles", n_both)
        addToTable(t, "Unc. particles", n_none)
        addToTable(t, "Junctions w/ particles", n_bp + n_both)
        addToTable(t, "Tips w/ particles", n_tip + n_both)
        addToTable(t, "Total skel. lenght", total_len)
        addToTable(t, "Total end points", len(end_points))
        addToTable(t, "Total junctions", sum(junctions))
        addToTable(t, "Unc. particles / Total skel. lenght)", n_none/total_len)
        addToTable(t, "Snap-to dist.", str(cutoff_dist) + impPart.getCalibration().getUnits())
        addToTable(t, "Threshold", "%d (%s)" % (threshold_lower, thres_method))
        showTable(t, "Results")
def import_and_straighten(imgDir):
    """
    Core function. Opens images in given directory in series and calls a straightening function.
    Thresholds using weka if stddev of pixel intensities is too high (bright field), otherwise uses
    histogram based segmentation.
    """
    targetWidth = 800 #adjustable
    make_directory(imgDir)
    index = "000000000"
    filename = imgDir + "/img_" + index + "__000.tif"
    if path.exists(filename):
        weka = Weka_segmentor(IJ.openImage(filename))
    while path.exists(filename):
        IJ.run("Set Measurements...", "mean standard min center redirect=None decimal=3")
        IJ.run("Clear Results")
        imp = IJ.openImage(filename)
        imp.show()
        IJ.run("Rotate 90 Degrees Left")
        IJ.run("Measure")
        table = RT.getResultsTable()
        stddev = RT.getValue(table, "StdDev", 0)

        if stddev < 20:
            segmented = weka.getThreshold(imp)
            segmented.show()
            IJ.run("8-bit")
            IJ.run("Invert")
            imp.close()
            imp = segmented

        else:
            IJ.run(imp, "Auto Threshold", "method=Li white") #threshold

        imp = preProcess_(imp)

        #straighten_roi_rotation()
        coords = run_straighten()

        newImp = IJ.getImage()
        """
        fs = FileSaver(newImp)
        fs.saveAsTiff(imgDir + "/straightened" + "/img_" + index + "__000-straight.tif")
        """

        IJ.run("Image Padder", "pad_right="+str(targetWidth - newImp.getWidth()))
        paddedImp = IJ.getImage()
        fs = FileSaver(paddedImp)
        fs.saveAsTiff(imgDir + "/binary" + "/img_" + index + "__000-padded.tif")

        IJ.runMacro("while (nImages>0) {selectImage(nImages);close();}")

        #use same centerline for original greyscale image
        imp = IJ.openImage(filename)
        imp.show()
        IJ.run("Rotate 90 Degrees Left")
        IJ.run("8-bit")
        IJ.runMacro("makeLine("+coords+")")
        IJ.run("Straighten...", "line = 80")
        newImp = IJ.getImage()
        IJ.run("Image Padder", "pad_right="+str(targetWidth - newImp.getWidth()))
        paddedImp = IJ.getImage()
        IJ.run("8-bit")
        fs = FileSaver(paddedImp)
        fs.saveAsTiff(imgDir + "/greyscale" + "/img_" + index + "__000-padded.tif")
        IJ.runMacro("while (nImages>0) {selectImage(nImages);close();}")

        index = to_9_Digits(str(int(index)+1))
        filename = filename = imgDir + "/img_" + index + "__000.tif"
Exemplo n.º 47
0
def run_comdet(image):
	IJ.run(image,"Detect Particles", " two=[Detect in both channels independently] ch1a="+str(ch1size) + " ch1s=" + str(ch1thresh) + " ch2a="+str(ch2size) + " ch2s=" + str(ch2thresh) + " calculate max=" + str(coloc) + " add=Nothing")
	rt = ResultsTable.getResultsTable()
	return rt