Beispiel #1
0
	def showimage(self):
		roim = RoiManager.getInstance()
		if roim is None:
			roim = RoiManager()
		IJ.run("Close All")
		IJ.run("Clear Results")
		try:
			roim.reset()
		except AttributeError:
			roim.runCommand("reset")
		obj = self.fcsimages[self.idximg][0]
		imgName = self.fcsimages[self.idximg][1]

		img =  BF.openImagePlus(imgName)[0]
		img.setZ(obj[1][2]+1)
		img.setC(3)
		IJ.run(img, "Grays", "");
		img.setC(1)
		img.show()

		#draw rois
		for i in range(1, len(obj)+1):
			PR = PointRoi(obj[i][0],obj[i][1])
			try:
				PR.setSize(3)
				PR.setPointType(0)
				roim.addRoi(PR)
			except:
				roim.addRoi(PR)
		roim.runCommand('Show All with Labels')
def run():
    global pmWin
    global imgData
    helpText = "This is Point Marker, " + \
               "a program for marking points in images.\n\n" + \
               ">> Press OK to Select a file for storing points infomation.\n"+\
               ">> TIF-Images within the same directory will be auto-loaded."
    MessageDialog(IJ.getInstance(), "Point Marker Guide", helpText)

    fileChooser = OpenDialog("Point Marker: Choose working directory and file")
    outfilePath = fileChooser.getPath()
    imgDir = fileChooser.getDirectory()
    if not imgDir: return
    imgPaths = []
    if imgDir:
        for root, directories, filenames in os.walk(imgDir):
            for filename in filenames:
                if not filename.endswith(".tif"):
                    continue
                imgPaths.append(os.path.join(root, filename))

    pointsTable1 = readPoints(outfilePath)

    imgData = PointMarkerData(imgPaths, outfilePath, pointsTable1)

    IJ.setTool("multipoint")
    PointRoi.setDefaultSize(3)

    pmWin = PointMarkerWin(imgData)
    pmWin.win.setLocation(IJ.getInstance().getLocation())
    prepareNewImage(imgData)
def run():
    global pmWin
    global imgData
    helpText = "This is Point Marker, " + \
               "a program for marking points in images.\n\n" + \
               ">> Press OK to Select a file for storing points infomation.\n"+\
               ">> TIF-Images within the same directory will be auto-loaded."
    MessageDialog(IJ.getInstance(),"Point Marker Guide", helpText)

    fileChooser = OpenDialog("Point Marker: Choose working directory and file")
    outfilePath = fileChooser.getPath()
    imgDir = fileChooser.getDirectory()
    if not imgDir:  return
    imgPaths = []
    if imgDir:
        for root, directories, filenames in os.walk(imgDir):
            for filename in filenames:
                if not filename.endswith(".tif"):
                    continue
                imgPaths.append(os.path.join(root, filename))

    pointsTable1 = readPoints(outfilePath)

    imgData = PointMarkerData(imgPaths, outfilePath, pointsTable1)

    IJ.setTool("multipoint")
    PointRoi.setDefaultSize(3)

    pmWin = PointMarkerWin(imgData)
    pmWin.win.setLocation(IJ.getInstance().getLocation())
    prepareNewImage(imgData)
Beispiel #4
0
def run():
    global maxDist, minPts

    ip = IJ.getImage()
    roi = ip.getRoi()
    points = roi.getContainedPoints()
    pointList = Arrays.asList(points)
    dplist = []
    for p in pointList:
        array = []
        array.append(p.x)
        array.append(p.y)
        jArray = jarray.array(array, 'd')
        dp = DoublePoint(jArray)
        dplist.append(dp)

    clusterer = DBSCANClusterer(maxDist, minPts)
    clusters = clusterer.cluster(dplist)
    RoiManager()
    roiManager = RoiManager.getRoiManager()
    for c in clusters:
        xCoordinates = []
        yCoordinates = []
        for dp in c.getPoints():
            p = dp.getPoint()
            xCoordinates.append(p[0])
            yCoordinates.append(p[1])
        roi = PointRoi(xCoordinates, yCoordinates)
        roiManager.addRoi(roi)
Beispiel #5
0
def scaleTypeROI(roi):
	if isinstance(roi,PointRoi):
		p=roi.getFloatPolygon()
		x,y=list(p.xpoints),list(p.ypoints)
		xNew,yNew=map(lambda c:c*scale[0],x),map(lambda c:c*scale[1],y)
		roiNew=PointRoi(xNew,yNew)
	elif isinstance(roi,ShapeRoi):
		roiSels=roi.getRois()
		roiNews=map(scaleTypeROI,roiSels)
		roiNew=0
		for roi in roiNews:
			if roiNew==0:
				roiNew=ShapeRoi(roi)
			else:
				roiNew=roiNew.or(ShapeRoi(roi))
	else:
		tp=roi.getType()
		if tp!=0:
			p=roi.getPolygon()
			x,y=list(p.xpoints),list(p.ypoints)
			posNew=map(lambda pos:(pos[0]*scale[0],pos[1]*scale[1]),zip(x,y))
			xNew,yNew=zip(*posNew)
			roiNew=PolygonRoi(xNew,yNew,tp)
		else:
			x,y,w,h=roi.getXBase(),roi.getYBase(),roi.getFloatWidth(),roi.getFloatHeight()
			xNew,yNew,wNew,hNew=x*scale[0],y*scale[1],w*scale[0],h*scale[1]
			roiNew=Roi(xNew,yNew,wNew,hNew)
	return(roiNew)
def drawLines(imp, points=None):
    if points and (len(points)%2 == 0):
        # points is numeric list of even length
        pRoi = PointRoi(points[0::2], points[1::2], len(points)/2)
        pRoi.setShowLabels(True)
        pRoi.setSize(3)
        imp.setRoi(pRoi)
    roi = imp.getRoi()
    pp = roi.getFloatPolygon()
    # print "Added", pp.npoints
    if pp.npoints <= 1:
        # don't draw if only one point
        return
    xys = []
    for i in xrange(pp.npoints):
        xys.append([pp.xpoints[i], pp.ypoints[i]])
    ol = Overlay()
    x0 = xys[0][0]
    y0 = xys[0][1]
    cal = imp.getCalibration()
    for i in xrange(1, pp.npoints):
        xi = xys[i][0]
        yi = xys[i][1]
        # prepare text label
        d = math.sqrt((xi - x0)**2 + (yi - y0)**2) * cal.pixelWidth
        dText = String.format("%.2f ", d) + cal.getUnits()
        textOffset = 30
        xt = xi
        yt = yi
#        if xi > x0:
#            xt += textOffset
        if xi < x0:
            xt -= textOffset
#        if yi > y0:
#            yt += textOffset
        if yi < y0:
            yt -= textOffset
        dTextRoi = TextRoi(xt, yt, dText)
        ol.add(dTextRoi)

        lineRoi = Line(x0, y0, xi, yi)
        lineRoi.setStrokeWidth(1)
        lineRoi.setStrokeColor(Color(255,255,0))
        ol.add(lineRoi)
    imp.setOverlay(ol)
    imp.updateAndDraw()
Beispiel #7
0
    def updatePointRoi(self):
        # Surround with try/except to prevent blocking
        #   ImageJ's stack slice updater thread in case of error.
        try:
            # Update PointRoi
            self.imp.killRoi()
            point = self.nuclei[self.imp.getFrame()]  # map 1-based slices
            # to 0-based nuclei Z coords

            if len(point) == 0:
                return
            IJ.log("Cell found in frame " + str(self.imp.getFrame()))
            # New empty PointRoi for the current slice
            roi = PointRoi(point[0], point[1])
            # Style: large, red dots
            roi.setSize(4)  # ranges 1-4
            roi.setPointType(2)  # 2 is a dot (filled circle)
            roi.setFillColor(Color.red)
            roi.setStrokeColor(Color.red)
            self.imp.setRoi(roi)
        except:
            IJ.error(sys.exc_info())
Beispiel #8
0
def draw_classes(inputfile,data):

    pathname,filename = os.path.split(inputfile)

    # last subdir is for well
    ## TODO ## support multiple plates, read plate and well from csv
    well = os.path.basename(pathname)

    # create output directory
    outputdir = os.path.join(OUTPUTROOT,well)
    if not os.path.isdir(outputdir):
        os.makedirs(outputdir)

    # create output filename
    head,tail = os.path.splitext(filename)
    outputfilename = head + "_classes" + tail
    outputfilename = os.path.join(outputdir,outputfilename)
    print outputfilename

    imp = IJ.openImage(inputfile).duplicate()
    IJ.run(imp,"RGB Color","")

    for d in data:
        x = int(float(d[0]))
        y = int(float(d[1]))
        c = int(float(d[2]))

        classname = classes[str(c)]
        colorname = colors[classname]
        color = colormap[colorname]
        #print colorname

        roi = PointRoi(x,y)
        roi.setDefaultMarkerSize("Large")
        roi.setStrokeColor(colormap[colorname])
        
        imp.getProcessor().drawRoi(roi)

    IJ.saveAs(imp,"png",outputfilename)
def drawLines(imp, points=None):
    if points and (len(points) % 2 == 0):
        # points is numeric list of even length
        pRoi = PointRoi(points[0::2], points[1::2], len(points) / 2)
        pRoi.setShowLabels(True)
        pRoi.setSize(3)
        imp.setRoi(pRoi)
    roi = imp.getRoi()
    pp = roi.getFloatPolygon()
    # print "Added", pp.npoints
    if pp.npoints <= 1:
        # don't draw if only one point
        return
    xys = []
    for i in xrange(pp.npoints):
        xys.append([pp.xpoints[i], pp.ypoints[i]])
    ol = Overlay()
    x0 = xys[0][0]
    y0 = xys[0][1]
    cal = imp.getCalibration()
    for i in xrange(1, pp.npoints):
        xi = xys[i][0]
        yi = xys[i][1]
        # prepare text label
        d = math.sqrt((xi - x0)**2 + (yi - y0)**2) * cal.pixelWidth
        dText = String.format("%.2f ", d) + cal.getUnits()
        textOffset = 30
        xt = xi
        yt = yi
        #        if xi > x0:
        #            xt += textOffset
        if xi < x0:
            xt -= textOffset


#        if yi > y0:
#            yt += textOffset
        if yi < y0:
            yt -= textOffset
        dTextRoi = TextRoi(xt, yt, dText)
        ol.add(dTextRoi)

        lineRoi = Line(x0, y0, xi, yi)
        lineRoi.setStrokeWidth(1)
        lineRoi.setStrokeColor(Color(255, 255, 0))
        ol.add(lineRoi)
    imp.setOverlay(ol)
    imp.updateAndDraw()
Beispiel #10
0
def process_img(img_path):
    IJ.log('Processing {} ...'.format(img_path))

    # open image
    imp = IJ.openImage(img_path)
    imp.show()
    w_big = imp.getWindow()
    w_big.setLocationAndSize(1050, 400, 500, 500)

    # read relative csv file rows (coordinates of centers)
    img_name, img_extension = os.path.splitext(img_path)
    marker_path = img_name + '.csv'

    if not os.path.exists(marker_path):
        root = os.path.dirname(marker_path)
        IJ.log('Creating corrected CSV files in {}...'.format(root))
        mrk.markers_to_csv(root, y_inv_height=imp.height)

    markers = mrk.read_marker(marker_path, to_int=True)

    for cs in gen_cell_stacks(imp, markers, cube_roi_dim, scaleZ):

        # identify cell in original image
        imp.setSlice(cs.seed[2] + 1)
        point = PointRoi(cs.seed[0], cs.seed[1])
        point.setSize(3)
        point.setColor(Color.RED)
        imp.setRoi(point)

        if discard_margin_cells:
            if not cs.onBorder:
                process_cell(cs)
            else:
                IJ.log('Skipped on border cell in seed ' + str(cs.seed))
        else:
            process_cell(cs)

        c = raw_input(
            "Press enter to show the next cell or 'n' to go to the next image\n"
        )

        cs.close()
        if c == 'n':
            IJ.log("Skipped remaining cells")
            break
Beispiel #11
0
def findEndPoints(imageID, maskID):
    endPoints1 = []
    endPoints2 = []

    imp = IJ.getImage()
    imp.setSlice(1);

    roiManager = RoiManager.getInstance2()
    rois = roiManager.getRoisAsArray()
    roisToBeRemoved = []
    index = 0
    for roi in rois:
       outerBounds = roi.getBounds()
       impMT, innerBounds = duplicateMaskInRoi(imp, roi)
       nr, endPoint1, endPoint2 = findEndPointsInSkeleton(impMT)
       if (nr==2):
           endPoint1.x = endPoint1.x + outerBounds.x + innerBounds.x - 1
           endPoint1.y = endPoint1.y + outerBounds.y + innerBounds.y - 1
           endPoint2.x = endPoint2.x + outerBounds.x + innerBounds.x - 1
           endPoint2.y = endPoint2.y + outerBounds.y + innerBounds.y - 1
           endPoints1.append(endPoint1)
           endPoints2.append(endPoint2)
       else:
           roisToBeRemoved.append(index)
       impMT.close()
       index = index + 1
    if (len(roisToBeRemoved)>0):
        roiManager.setSelectedIndexes(roisToBeRemoved)
        roiManager.runCommand("Delete")
    roiManager.moveRoisToOverlay(WindowManager.getImage(maskID))
    inputIMP = WindowManager.getImage(imageID)
    inputIMP.setOverlay(PointRoi([seq.x for seq in endPoints1], [seq.y for seq in endPoints1]), Color.magenta, 1, Color.magenta)
    otherPoints = PointRoi([seq.x for seq in endPoints2], [seq.y for seq in endPoints2])
    otherPoints.setStrokeColor(Color.cyan)
    otherPoints.setFillColor(Color.cyan)
    inputIMP.getOverlay().add(otherPoints)
from ij.plugin.frame import RoiManager
from ij import WindowManager
from ij.gui import PointRoi,ShapeRoi

roiManager=WindowManager.getFrame("ROI Manager")
roiSel=roiManager.getSelectedRoisAsArray()
if len(roiSel)==1:
	roiSel=roiSel[0].getRois()
	roiSel=map(ShapeRoi,roiSel) # convert roi composite to many roi
x,y=[],[]
for sel in roiSel:
	stat=sel.getStatistics()
	x.append(stat.xCentroid)
	y.append(stat.yCentroid)
roi_new=PointRoi(x,y)
roiManager.addRoi(roi_new)
Beispiel #13
0
def ana_particles_watershed(imp,
                            strThrMeth="method=Default white",
                            minPx=10,
                            minCirc=0.35,
                            labCol=Color.white,
                            linCol=Color.green,
                            bDebug=False,
                            sl=0.005):
    """ana_particles_watershed(imp, strThrMeth="method=Default white", minPx=10, minCirc=0.35, labCol=Color.white, linCol=Color.green, bDebug=False, sl=0.005)
	A wrapper function to do particle analysis from an image after a watershed transformation and draw the detected
	features into the overlay of the original image.
	Inputs:
	imp        - the ImagePlus instance that we will process
	strThrMeth - a string specifying the threshold method
	minPx      - the minimum pixels to detect
	minCirc    - the minimum circularity to detect
	labCol     - the color for labels in the overlay (default white)
	linCol     - the color for line/stroke in the overlay (default green)
	bDebug     - a flag (default False) that, if true, keeps the work image open
	sl         - a time (default 0.005) to sleep when adding ROIs to not overload
	
	This adds the detected features to the overlay and returns the result table for
	processing for output.
	"""

    title = imp.getTitle()
    shortTitle = imp.getShortTitle()
    typ = imp.getType()
    imp.setTitle(shortTitle)
    imp.show()
    IJ.run(imp, "Duplicate...", "title=work")
    wrk = IJ.getImage()
    # if this is a 16 bit image, convert to 8 bit prior to threshold
    if typ == ImagePlus.GRAY16:
        IJ.run(wrk, "Enhance Contrast", "saturated=0.35")
        IJ.run(wrk, "8-bit", "")
        IJ.run(wrk, "Threshold", strThrMeth)
        IJ.run(wrk, "Watershed", "")

    wrk.show()
    strMeas = "area mean modal min center perimeter bounding fit shape feret's display redirect=%s decimal=3" % shortTitle
    IJ.run(wrk, "Set Measurements...", strMeas)
    strAna = "size=%d-Infinity circularity=%g-1.00  exclude clear include add" % (
        minPx, minCirc)
    IJ.run(wrk, "Analyze Particles...", strAna)
    rt = ResultsTable().getResultsTable()
    rm = RoiManager.getInstance()
    ra = rm.getRoisAsArray()
    # Draw the particles into the overlay of the original
    i = 0
    for r in ra:
        i += 1
        rLab = "%d" % i
        r.setName(rLab)
        imp = jmg.addRoiToOverlay(imp, r, labCol=labCol, linCol=linCol)
        # needed to put in sleep here on crunch to let this complete and not overrun buffer
        time.sleep(sl)

    # let's put a PointRoi outside the image to get the overlays all the same color
    r = PointRoi(-10, -10)
    imp = jmg.addRoiToOverlay(imp, r, labCol=labCol, linCol=linCol)
    # clear the roi manager and return the results table
    rm.reset()
    rm.close()
    imp.setTitle(title)
    if bDebug == False:
        wrk.changes = False
        wrk.close()
    return r
def extractFeatures(ip, params):
  sift = FloatArray2DSIFT(params)
  sift.init(FloatArray2D(ip.convertToFloat().getPixels(),
                         ip.getWidth(), ip.getHeight()))
  features = sift.run() # instances of mpicbg.imagefeatures.Feature
  return features

features1 = extractFeatures(imp1.getProcessor(), p)
features2 = extractFeatures(imp2.getProcessor(), p)

# Feature locations as points in an ROI
# Store feature locations in the Roi manager for visualization later
roi_manager = RoiManager()

roi1 = PointRoi()
roi1.setName("features for cut1")
for f in features1:
  roi1.addPoint(f.location[0], f.location[1])

roi_manager.addRoi(roi1)

roi2 = PointRoi()
roi2.setName("features for cut2")
for f in features2:
  roi2.addPoint(f.location[0], f.location[1])

roi_manager.addRoi(roi2)

# Find matches between the two sets of features
# (only by whether the properties of the features themselves match,
def getSpots(imp,
             channel,
             detector_type,
             radius,
             threshold,
             overlay,
             roi_type="large",
             roi_color=ColorRGB("blue")):
    """ Performs the detection, adding spots to the image overlay
    :imp:           The image (ImagePlus) being analyzed
    :channel:       The target channel
    :detector_type: A string describing the detector: "LoG" or "DoG"
    :radius:        Spot radius (NB: trackmate GUI accepts diameter)
    :threshold:     Quality cutoff value
    :overlay:       The image overlay to store spot (MultiPoint) ROIs
    :roi_type:      A string describing how spot ROIs should be displayed
    :returns:       The n. of detected spots
    """
    settings = Settings()
    settings.setFrom(imp)
    settings.detectorFactory = (LogDetectorFactory() if "LoG" in detector_type
                                else DogDetectorFactory())
    settings.detectorSettings = {
        DK.KEY_DO_SUBPIXEL_LOCALIZATION: False,
        DK.KEY_DO_MEDIAN_FILTERING: True,
        DK.KEY_TARGET_CHANNEL: channel,
        DK.KEY_RADIUS: radius,
        DK.KEY_THRESHOLD: threshold,
    }
    trackmate = TrackMate(settings)
    if not trackmate.execDetection():
        lservice.error(str(trackmate.getErrorMessage()))
        return 0
    model = trackmate.model
    spots = model.getSpots()
    count = spots.getNSpots(False)
    ch_id = "Spots Ch%d" % channel
    if count > 0:
        roi = None
        cal = imp.getCalibration()
        t_pos = imp.getT()
        if (t_pos > 1):
            lservice.warn("Only frame %d was considered..." % t_pos)
        for spot in spots.iterable(False):
            x = cal.getRawX(spot.getFeature(spot.POSITION_X))
            y = cal.getRawY(spot.getFeature(spot.POSITION_Y))
            z = spot.getFeature(spot.POSITION_Z)
            if z == 0 or not cal.pixelDepth or cal.pixelDepth == 0:
                z = 1
            else:
                z = int(z // cal.pixelDepth)
            imp.setPosition(channel, z, t_pos)
            if roi is None:
                roi = PointRoi(int(x), int(y), imp)
            else:
                roi.addPoint(imp, x, y)
        roi.setStrokeColor(colorRGBtoColor(roi_color))
        if "large" in roi_type:
            roi.setPointType(3)
            roi.setSize(4)
        else:
            roi.setPointType(2)
            roi.setSize(1)
        overlay.add(roi, ch_id)
    return count
Beispiel #16
0
    peaks = detector.getResult()
    print str(len(peaks)), "peaks were found."

    # Add points to ROI manager
    rm = RoiManager.getInstance()
    if not rm:
        rm = RoiManager()

    # Loop through all the peak that were found
    for peak in peaks:
        # Print the current coordinates
        print "peaks", peak.getDoublePosition(0), peak.getDoublePosition(
            1), peak.getDoublePosition(2)
        # Add the current peak to the Roi manager
        roi = PointRoi(
            peak.getDoublePosition(0) / cal.pixelWidth,
            peak.getDoublePosition(1) / cal.pixelHeight)
        oval = OvalRoi(
            int(
                peak.getDoublePosition(0) / cal.pixelWidth -
                0.5 * radius / cal.pixelWidth),
            int(
                peak.getDoublePosition(1) / cal.pixelHeight -
                0.5 * radius / cal.pixelHeight), radius / cal.pixelWidth,
            radius / cal.pixelHeight)
        oval.setColor(Color.RED)
        # Set the Z position of the peak otherwise the peaks are all set on the same slice
        oval.setPosition(
            int(round(peak.getDoublePosition(2) / cal.pixelDepth)) + 1)
        roi.setPosition(
            int(round(peak.getDoublePosition(2) / cal.pixelDepth)) + 1)
Beispiel #17
0
               for i in range(img.numDimensions())]  # no calibration: identity
sigmaSmaller = 15  # in pixels: a quarter of the radius of an embryo
sigmaLarger = 30  # pixels: half the radius of an embryo
extremaType = DogDetection.ExtremaType.MAXIMA
minPeakValue = 10
normalizedMinPeakValue = False

# In the differece of gaussian peak detection, the img acts as the interval
# within which to look for peaks. The processing is done on the infinite imgE.
dog = DogDetection(imgE, img, calibration, sigmaSmaller, sigmaLarger,
                   extremaType, minPeakValue, normalizedMinPeakValue)

peaks = dog.getPeaks()

# Create a PointRoi from the DoG peaks, for visualization
roi = PointRoi(0, 0)
# A temporary array of integers, one per dimension the image has
p = zeros(img.numDimensions(), 'i')
# Load every peak as a point in the PointRoi
for peak in peaks:
    # Read peak coordinates into an array of integers
    peak.localize(p)
    roi.addPoint(imp, p[0], p[1])

imp.setRoi(roi)

# Now, iterate each peak, defining a small interval centered at each peak,
# and measure the sum of total pixel intensity,
# and display the results in an ImageJ ResultTable.
table = ResultsTable()
Beispiel #18
0
def main(imp, tolerance, window_radius, pixel_size_nm, out_dir):
	# set output dir
	out_dir = str(out_dir)
	
	# Find maxima
	excludeOnEdge = True
	polygon = MaximumFinder().getMaxima(imp.getProcessor(), tolerance, excludeOnEdge)
	roi = PointRoi(polygon)

	# get RoiManager
	rm = RoiManager.getInstance();
	if rm is None:
	    rm = RoiManager()

	# Check if output table is writable
	out_table_fn = os.path.join(out_dir, "fwhm_values.txt")
	try:
		file_handle = open(out_table_fn, 'w')
	except IOError:
		IJ.showMessage("Output file '' not writeable. Check if file is open in Excel...")
		sys.exit(0)
				
	
	# iterate and write output
	with file_handle as csvfile:
		writer = csv.DictWriter(csvfile, 
		                        fieldnames=["id", "peak_id", "x_pos", "y_pos", 
		                                    "type", "fwhm", "fwhm_nm", "r2_GoF", 
		                                    "avg_fwhm", "area_profile", "area_gauss"], delimiter="\t", lineterminator='\n')
		writer.writeheader()
		id_ = 0
		# over all peaks
		for i, p in list(enumerate(roi)):
			IJ.showProgress(i, roi.getNCounters() +1)
			
			# Horizontal
			lroi = Line(p.x+0.5-window_radius, p.y+0.5, 
			            p.x+0.5+window_radius, p.y+0.5)
			output = fit_gauss(lroi, imp, p, i, id_, "H", rm)
			writer.writerow(output)
			id_+=1

			# Vertical
			lroi = Line(p.x+0.5, p.y+0.5-window_radius, 
			            p.x+0.5, p.y+0.5+window_radius)
			output = fit_gauss(lroi, imp, p, i, id_, "V", rm)
			writer.writerow(output)
			id_+=1

			# Diagonal 1
			lroi = Line(p.x+0.5-MN*window_radius, p.y+0.5+MN*window_radius, 
			            p.x+0.5+MN*window_radius, p.y+0.5-MN*window_radius)
			output = fit_gauss(lroi, imp, p, i, id_, "D1", rm)
			writer.writerow(output)
			id_+=1

			# Diagonal 2
			lroi = Line(p.x+0.5-MN*window_radius, p.y+0.5-MN*window_radius, 
			            p.x+0.5+MN*window_radius, p.y+0.5+MN*window_radius)
			output = fit_gauss(lroi, imp, p, i, id_, "D2", rm)
			writer.writerow(output)
			id_+=1
			
	IJ.showProgress(1)
	
	rm.runCommand("Deselect"); # deselect ROIs to save them all
	rm.runCommand("Save", os.path.join(out_dir, "fwhm_fiji_rois.zip"))
	
	IJ.showMessage("FWHM on Spots: Done")
Beispiel #19
0
f = open(str(xFile))
for line in f:
	x.append(line.replace("\n","").split(","))
f.close()

f = open(str(yFile))
for line in f:
	y.append(line.replace("\n","").split(","))
f.close()

f = open(str(zFile))
for line in f:
	z.append(line.replace("\n","").split(","))
f.close()

x.pop(0)
y.pop(0)
z.pop(0)

imp = IJ.getImage()
rm = RoiManager()

IJ.log("Processing started")
for point in x:
	IJ.log("\\Update:Processing Object {}/{}".format(x.index(point)+1,len(x)))
	for time in point:
		if len(time) < 10 and time != 'NA':
			imp.setZ(int(round(float(z[x.index(point)][x[x.index(point)].index(time)]))))
			imp.setT(x[x.index(point)].index(time)+1)
			rm.add(imp,PointRoi(int(round(float(time))),int(round(float(y[x.index(point)][x[x.index(point)].index(time)])))),x.index(point)+1)
Beispiel #20
0
def process(srcDir, dstDir, currentDir, fileName, keepDirectories, Channel_1, Channel_2, radius_background, sigmaSmaller, sigmaLarger, minPeakValue, min_dist):
 	IJ.run("Close All", "")

 	# Opening the image
 	IJ.log("Open image file:" + fileName)
 	#imp = IJ.openImage(os.path.join(currentDir, fileName))
	#imp = IJ.getImage()
	imp = BF.openImagePlus(os.path.join(currentDir, fileName))
	imp = imp[0]

	# getDimensions(width, height, channels, slices, frames)

	IJ.log("Computing Max Intensity Projection")

	if imp.getDimensions()[3] > 1:
		imp_max = ZProjector.run(imp,"max")
	else:
		imp_max = imp

	ip1, ip2 = extract_channel(imp_max, Channel_1, Channel_2)

	IJ.log("Substract background")

	imp1, imp2 = back_substraction(ip1, ip2, radius_background)

	IJ.log("Finding Peaks")

	ip1_1, ip2_1, peaks_1, peaks_2 = find_peaks(imp1, imp2, sigmaSmaller, sigmaLarger, minPeakValue)

	# Create a PointRoi from the DoG peaks, for visualization
	roi_1 = PointRoi(0, 0)
	roi_2 = PointRoi(0, 0)
	roi_3 = PointRoi(0, 0)
	roi_4 = PointRoi(0, 0)

	# A temporary array of integers, one per dimension the image has
	p_1 = zeros(ip1_1.numDimensions(), 'i')
	p_2 = zeros(ip2_1.numDimensions(), 'i')


	# Load every peak as a point in the PointRoi
	for peak in peaks_1:
	  # Read peak coordinates into an array of integers
	  peak.localize(p_1)
	  roi_1.addPoint(imp1, p_1[0], p_1[1])

	for peak in peaks_2:
	  # Read peak coordinates into an array of integers
	  peak.localize(p_2)
	  roi_2.addPoint(imp2, p_2[0], p_2[1])

	# Chose minimum distance in pixel
	#min_dist = 20

	for peak_1 in peaks_1:
		peak_1.localize(p_1)
		for peak_2 in peaks_2:
			peak_2.localize(p_2)
			d1 = distance(p_1, p_2)
			if  d1 < min_dist:
				roi_3.addPoint(imp1, p_2[0], p_2[1])
				break

	for peak_2 in peaks_2:
		peak_2.localize(p_2)
		for peak_1 in peaks_1:
			peak_1.localize(p_1)
			d2 = distance(p_2, p_1)
			if  d2 < min_dist:
				roi_4.addPoint(imp1, p_2[0], p_2[1])
				break

	cal = imp.getCalibration()
	min_distance = str(round((cal.pixelWidth * min_dist),1))

	table = ResultsTable()
	table.incrementCounter()
	table.addValue("Numbers of Neuron Markers", roi_1.getCount(0))
	table.addValue("Numbers of Glioma Markers", roi_2.getCount(0))
	table.addValue("Numbers of Glioma within %s um of Neurons" %(min_distance), roi_3.getCount(0))
	table.addValue("Numbers of Neurons within %s um of Glioma" %(min_distance), roi_4.getCount(0))
	#table.show("Results Analysis")
	saveDir = currentDir.replace(srcDir, dstDir) if keepDirectories else dstDir
	if not os.path.exists(saveDir):
		os.makedirs(saveDir)
	IJ.log("Saving to" + saveDir)
	table.save(os.path.join(saveDir, fileName + ".csv"))
	IJ.selectWindow("Log")
	IJ.saveAs("Text", os.path.join(saveDir, fileName + ".csv"));
Beispiel #21
0
def save_membrane_edge_image(membrane_channel_imp, fixed_anchors_list,
                             membrane_edges, area_rois, params):
    """Save an image with the membrane channel overlaid with original anchor positions, fixed anchor positions, and membrane edge"""
    IJ.run(membrane_channel_imp, "RGB Color", "")
    anchors = params.manual_anchor_positions
    midpoint = params.manual_anchor_midpoint[0]
    #print("membrane_edges = " + str(len(membrane_edges)));
    #print("membrane_channel_imp = " + str(membrane_channel_imp));
    #print("fixed_anchors_list = " + str(len(fixed_anchors_list)));
    #print("area_rois = " + str(len(area_rois)));
    if fixed_anchors_list is None:
        fixed_anchors_list = []  # not pythonic, but never mind...
        for edge in membrane_edges:
            poly = edge.getPolygon()
            xs = poly.xpoints
            ys = poly.ypoints
            fixed_anchors_list.append([(xs[0], ys[0]), (xs[-1], ys[-1])])
    try:
        for fridx in range(0, membrane_channel_imp.getNFrames()):
            membrane_channel_imp.setPosition(fridx + 1)
            membrane_channel_imp.setRoi(membrane_edges[fridx])
            IJ.setForegroundColor(0, 255, 255)
            IJ.run(membrane_channel_imp, "Draw", "slice")
            membrane_channel_imp.setRoi(area_rois[fridx])
            IJ.setForegroundColor(0, 255, 0)
            IJ.run(membrane_channel_imp, "Draw", "slice")
            for p in anchors:
                roi = PointRoi(p[0], p[1])
                membrane_channel_imp.setRoi(roi)
                IJ.setForegroundColor(255, 0, 0)
                IJ.run(membrane_channel_imp, "Draw", "slice")
            roi = PointRoi(midpoint[0], midpoint[1])
            membrane_channel_imp.setRoi(roi)
            IJ.setForegroundColor(255, 0, 0)
            IJ.run(membrane_channel_imp, "Draw", "slice")
            for p in fixed_anchors_list[fridx]:
                roi = PointRoi(p[0], p[1])
                membrane_channel_imp.setRoi(roi)
                IJ.setForegroundColor(255, 255, 0)
                IJ.run(membrane_channel_imp, "Draw", "slice")
            # TODO: if coincidence between anchors and fixed anchors, or indeed with edge, consider
            # rendering in secondary colours (magenta = (255,0,255), orange = (255,200,0), green = (0,255,0)?
    except:
        pass
    FileSaver(membrane_channel_imp).saveAsTiff(
        os.path.join(params.output_path, "membrane identification check.tif"))
    IJ.setForegroundColor(255, 255, 255)


#from ij import WindowManager as WM
#import membrane_blebbing_fileio as mbio;
#from ij.plugin import ChannelSplitter

#folder = "D:\\data\\Inverse blebbing\\output\\2018-10-29 17-06-15 output";
#curvature_overlay = IJ.openImage(os.path.join(folder, "raw curvature.tif"));
#curvature_profiles = mbio.load_csv_as_profile(os.path.join(folder, "curvatures.csv"));
#imp = IJ.openImage("D:\\data\\Inverse blebbing\\MAX_2dpf marcksl1b-EGFP inj_TgLifeact-mCh_movie e4_split-bleb1.tif");
#intensity_channel_imp = ChannelSplitter.split(imp)[1];
#intensity_channel_imp.show();
#colormap_string = "physics"

#generate_intensity_weighted_curvature(curvature_overlay, curvature_profiles, intensity_channel_imp, colormap_string);
Beispiel #22
0
               for i in range(img.numDimensions())]  # no calibration: identity
sigmaSmaller = 15  # in pixels: a quarter of the radius of an embryo
sigmaLarger = 30  # pixels: half the radius of an embryo
extremaType = DogDetection.ExtremaType.MAXIMA
minPeakValue = 10
normalizedMinPeakValue = False

# In the differece of gaussian peak detection, the img acts as the interval
# within which to look for peaks. The processing is done on the infinite imgE.
dog = DogDetection(imgE, img, calibration, sigmaSmaller, sigmaLarger,
                   extremaType, minPeakValue, normalizedMinPeakValue)

peaks = dog.getPeaks()

# Create a PointRoi from the DoG peaks, for visualization
roi = PointRoi(0, 0)
# A temporary array of integers, one per dimension the image has
p = zeros(img.numDimensions(), 'i')
# Load every peak as a point in the PointRoi
for peak in peaks:
    # Read peak coordinates into an array of integers
    peak.localize(p)
    roi.addPoint(imp, p[0], p[1])

imp.setRoi(roi)

# Now, iterate each peak, defining a small interval centered at each peak,
# and measure the sum of total pixel intensity,
# and display the results in an ImageJ ResultTable.
table = ResultsTable()
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 perform_user_qc(in_imp, edges, alt_edges, fixed_anchors_list, params):
	"""allow the user to intervene to fix erroneously identified membrane edges"""
	n_frames = in_imp.getNFrames();
	n_channels = in_imp.getNChannels();
	output_folder = params.output_path;
	current_edges = edges;
	rgbstack = ImageStack(in_imp.getWidth(), in_imp.getHeight());
	if n_frames > 1:
		for tidx in range(n_frames): 
			in_imp.setT(tidx+1);
			ip = in_imp.getProcessor();
			rgbip = ip.convertToRGB();
			rgbstack.addSlice(rgbip);
	else:
		for cidx in range(n_channels):
			in_imp.setC(cidx+1);
			ip = in_imp.getProcessor();
			rgbip = ip.convertToRGB();
			rgbstack.addSlice(rgbip);
	imp = ImagePlus(("RGB " + in_imp.getTitle()), rgbstack);
	IJ.run("Colors...", "foreground=red background=white selection=yellow");
	for tidx in range(imp.getNSlices()):
		imp.setSlice(tidx+1);
		for anchor in params.manual_anchor_positions:
			imp.setRoi(PointRoi(anchor[0], anchor[1]));
			IJ.run(imp, "Draw", "slice");
	imp.show();
	autoset_zoom(imp);
	imp.setPosition(1);
	imp.setRoi(current_edges[0]);
	if n_frames > 1:
		listener = UpdateRoiImageListener(current_edges);
		imp.addImageListener(listener);
	IJ.setTool("freeline");
	do_flip = True;
	while do_flip:
		dialog = NonBlockingGenericDialog("User quality control");
		dialog.enableYesNoCancel("Continue", "Flip all edges");
		dialog.setCancelLabel("Cancel analysis");
		dialog.addMessage("Please redraw the membrane edges as necessary, \n" + 
						"making sure to draw beyond anchor points at either end...\n" + 
						"Click OK when done. ");
		p = Panel();
		but = Button("Flip this edge");
		al = Listener(edges, alt_edges, imp);
		but.addActionListener(al);
		p.add(but);
		dialog.addPanel(p);
		dialog.showDialog();
		if dialog.wasCanceled():
			raise KeyboardInterrupt("Run canceled");
		elif dialog.wasOKed():
			do_flip = False;
		else:
			print("flip edges");
			do_flip = True;
			if n_frames > 1:
				imp.removeImageListener(listener);
			current_edges = alt_edges if (current_edges == edges) else edges;
			imp.setPosition(1);
			imp.setRoi(current_edges[0]);
			if n_frames > 1:
				listener = UpdateRoiImageListener(current_edges);
				imp.addImageListener(listener);

	last_roi = imp.getRoi();
	if n_frames > 1:
		qcd_edges = listener.getRoiList();
		if imp.getNFrames() > imp.getNSlices():
			qcd_edges[imp.getT() - 1] = last_roi;
		else:
			qcd_edges[imp.getZ() - 1] = last_roi;
		imp.removeImageListener(listener);
	else:
		qcd_edges = [last_roi];
	mbio.save_qcd_edges2(qcd_edges, output_folder);
	# next four lines are a quick and dirty hack...
	if n_frames > 1:
		nframes = imp.getNFrames() if imp.getNFrames()>imp.getNSlices() else imp.getNSlices();
	else:
		nframes = n_frames;
	for fridx in range(0, nframes):
		if (qcd_edges[fridx].getType()==Roi.FREELINE) or (qcd_edges[fridx].getType()==Roi.POLYLINE):
			if (fridx == 0) or params.constrain_anchors:
				anchors = params.manual_anchor_positions;
			else:
				anchors = fixed_anchors_list[fridx - 1];
			fixed_anchors = mb.fix_anchors_to_membrane(anchors, qcd_edges[fridx], params);
			fixed_anchors = mb.order_anchors(fixed_anchors, params.manual_anchor_midpoint);
			fixed_anchors_list[fridx] = fixed_anchors;
			poly =  qcd_edges[fridx].getInterpolatedPolygon(0.25, False);
			polypoints = [(x,y) for x,y in zip(poly.xpoints, poly.ypoints)];
			idx = [polypoints.index(fixed_anchors[0]), polypoints.index(fixed_anchors[1])];
			idx.sort();
			polypoints = polypoints[idx[0]:idx[1]];
			newedge = PolygonRoi([x for (x,y) in polypoints], 
									[y for (x,y) in polypoints], 
									Roi.POLYLINE);
			newedge = mb.check_edge_order(anchors, newedge);
			imp.setPosition(fridx + 1);
			imp.setRoi(newedge);
			IJ.run(imp, "Interpolate", "interval=1.0 smooth adjust");
			IJ.run(imp, "Fit Spline", "");
			qcd_edges[fridx] = imp.getRoi();
	mbio.save_qcd_edges2(qcd_edges, output_folder);
	imp.changes = False;
	imp.close();
	return qcd_edges, fixed_anchors_list;
def main():
	# ensure consistent preference settings
	Prefs.blackBackground = False;
	
	# get locations for previous and new outputs
	params = Parameters();
	params.loadLastParams();
	output_folder_old, output_folder = mbio.rerun_location_chooser(params.input_image_path);
	params.loadParametersFromJson(os.path.join(output_folder_old, 'parameters used.json'));
	params.setOutputPath(output_folder);

	# get original image file (for overlays etc.) 
	if not os.path.isfile(params.input_image_path):
		mbui.warning_dialog(["The original data can't be found at the location specified in saved parameters. ", 
							"(Possibly something as simple as a change in network drive mapping has occurred)",
							"Please specify the location of the original image file..."]);
		params.setInputImagePath(mbio.input_file_location_chooser(params.output_path));

	import_opts, params = mbui.choose_series(params.input_image_path, params);
	imps = bf.openImagePlus(import_opts);
	imp = imps[0];

	if imp.getNSlices() > 1:
		mbui.warning_dialog(["More than one Z plane detected.", 
							"I will do a maximum projection before proceeding", 
							"Continue?"]);
		imp = ZProjector.run(imp,"max all");

	# prompt user to select ROI
	original_imp = Duplicator().run(imp);
	_, crop_params = mbui.crop_to_ROI(imp, params);
	imp.show();

	if crop_params is not None:
		params.perform_spatial_crop = True;
		mbui.autoset_zoom(imp);
		imp.updateAndDraw();
		review_crop = mb.check_cropping(output_folder_old, params);
		keep_crop = not review_crop;
		if review_crop:
			keep_crop = mbui.crop_review();
		if not keep_crop:
			imp.changes = False;
			imp.close();
			imp = original_imp;
		else:
			original_imp.close();
	else:
		original_imp.close();

	# prompt user to do time cropping
	imp, start_end_tuple = mbui.time_crop(imp, params);
	params.setTimeCropStartEnd(start_end_tuple);

	params = mbio.get_metadata(params);
	params.setCurvatureLengthUm(round(params.curvature_length_um / params.pixel_physical_size) * params.pixel_physical_size);
	params.persistParameters();
	IJ.run(imp, "Set Scale...", "distance=0 known=0 pixel=1 unit=pixel");
	imp.show();
	if imp.getNChannels() > 1:
		imp.setPosition(params.membrane_channel_number, 1, 1);
	mbui.autoset_zoom(imp);
	IJ.run("Enhance Contrast", "saturated=0.35");

	split_channels = mbfs.split_image_plus(imp, params);
	membrane_test_channel_imp = Duplicator().run(split_channels[0]);
	segmentation_channel_imp = split_channels[-1];

	# import edges
	imp.hide();
	membrane_edges = mbio.load_qcd_edges2(os.path.join(output_folder_old, "user_defined_edges.zip"));
	dummy_anchors = [params.manual_anchor_positions for _ in membrane_edges]
	membrane_edges, fixed_anchors = mbui.perform_user_qc(membrane_test_channel_imp, membrane_edges, membrane_edges, dummy_anchors, params);
	imp.show();
	rgbstack = ImageStack(imp.getWidth(), imp.getHeight());
	for tidx in range(imp.getNFrames()): 
		imp.setT(tidx+1);
		ip = imp.getProcessor();
		rgbip = ip.convertToRGB();
		rgbstack.addSlice(rgbip);
	rgbimp = ImagePlus(("RGB " + imp.getTitle()), rgbstack);
	imp.close();
	rgbimp.show();
	IJ.run("Colors...", "foreground=yellow background=white selection=yellow");
	for tidx in range(rgbimp.getNSlices()):
		rgbimp.setSlice(tidx+1);
		rgbimp.setRoi(membrane_edges[tidx]);
		IJ.run(rgbimp, "Draw", "slice");
	IJ.run("Colors...", "foreground=red background=white selection=yellow");
	for tidx in range(rgbimp.getNSlices()):
		rgbimp.setSlice(tidx+1);
		for anchor in params.manual_anchor_positions:
			rgbimp.setRoi(PointRoi(anchor[0], anchor[1]));
			IJ.run(rgbimp, "Draw", "slice");
	params.saveParametersToJson(os.path.join(params.output_path, "parameters used.json"));
	params.persistParameters();	
	rgbimp.changes = False;
    print "building roi list"
    manager = RoiManager.getInstance()
    if (manager == None):
        manager = RoiManager()
    RoiManager(False)  #sho the roi manager window, wierd interface
    i = 1
    for currPoint in pointList:
        #print "point " + str(i)
        x, y, z = currPoint.split(",")

        #composite is interleaved with ch1/ch2
        #if doComposite==1:
        #	z *= 2

        #a point roi (This seems to be in pixels???)
        pROI = PointRoi(int(x), int(y), imp1)

        imp1.setSliceWithoutUpdate(int(z))
        manager.add(imp1, pROI,
                    int(z))  #add WITH slice, I want the pROI to be a 3D point
        #manager.addRoi(pROI) #add WITHOUT slice
        i += 1
    print "added " + str(i) + " pnts to roi manager"

if do3d == 1:
    #see: http://www.ini.uzh.ch/~acardona/fiji-tutorial/
    ps = []  #list of Point3f (pointList)
    cps = []  #list of Point3f of connection points (cPointList)
    lps = []  #list of backbone centerline points (lPointList)

    cell_diameter = 3  #right now in pixels, eventually in um
def main(imp,options):
	from ij.plugin import ChannelSplitter
	from ij.gui import Roi,PointRoi, PolygonRoi, Overlay, Line
	from java.awt import Color
	from ij import WindowManager
	from ij.measure import ResultsTable
	from ij.text import TextWindow
	active_z=imp.getZ()
	imps = ChannelSplitter.split(imp)
	imp.setZ(active_z)
	roi_int = imp.getRoi()


	comp_imp=Zproj(imps[options["comp_ch"]],
		"SUM",
		active_z,
		options["z_range"])
	comp_imp=mode_subtract(comp_imp,roi_int)

	loci_imp=Zproj(imps[options["loci_ch"]],
		"SUM",
		imp.getZ(),
		options["z_range"])
	loci_imp=mode_subtract(loci_imp,roi_int)

	#Finding the boundaries of compartment and loci
	comp_roi=thresh(sum_prj=comp_imp,thresh=options["comp_T"],roi=roi_int,method="boundary")
	print "ok"
	if (options["loci_method"]== "locus center"):
		loci_roi=thresh(sum_prj=loci_imp,
			thresh=options["loci_T"],
			roi=roi_int,
			method="point")
	elif options["loci_method"]== "locus boundary":
		loci_roi=thresh(sum_prj=loci_imp,
			thresh=options["loci_T"],
			roi=roi_int,
			method="boundary")
		
	
	if options["loci_method"]== "locus center":
		dist,xc,yc,xl,yl=get_center_edge_dist(imp,comp_roi, loci_roi)
	elif options["loci_method"]== "locus boundary":
		dist,xc,yc,xl,yl=get_closest_points(imp,comp_roi,loci_roi)


	rt_exist = WindowManager.getWindow("Loci distance to compartment")
	
	if rt_exist==None or not isinstance(rt_exist, TextWindow):
		table= ResultsTable()
	else:
		table = rt_exist.getTextPanel().getOrCreateResultsTable()
	table.incrementCounter()
	table.addValue("Label", imp.title)
	table.addValue("Distance(micron)", dist)
	
	if options['measure_feret']:
		feret_roi,loci_feret,loci_area= feret(sum_prj=loci_imp,thresh=options["loci_T"],
		roi=roi_int,pixel_size=imp.getCalibration().pixelWidth)
		table.addValue("Loci feret", loci_feret)
		table.addValue("Loci area", loci_area)
		
		
	table.show("Loci distance to compartment")

	## Adding loci overlay
	ov=imp.getOverlay()
	if ov==None:
		ov=Overlay()
	line = Line(xc,yc, xl,yl)
	line.setStrokeWidth(0.2)
	line.setStrokeColor(Color.PINK)
	ov.add(line)

	
	if options["loci_method"]== "locus center":
		ov.add(PointRoi(loci_roi["x"],loci_roi["y"]))
	elif options["loci_method"]== "locus boundary":
		ov.add(loci_roi)
	if options['measure_feret']:
		ov.add(feret_roi)
	ov.add(comp_roi)
	imp.setOverlay(ov)	
Beispiel #28
0
def getSpots(imp, channel, detector_type, radius, threshold, overlay,
             roi_type="large", roi_color=ColorRGB("blue")):
    """ Performs the detection, adding spots to the image overlay
    :imp:           The image (ImagePlus) being analyzed
    :channel:       The target channel
    :detector_type: A string describing the detector: "LoG" or "DoG"
    :radius:        Spot radius (NB: trackmate GUI accepts diameter)
    :threshold:     Quality cutoff value
    :overlay:       The image overlay to store spot (MultiPoint) ROIs
    :roi_type:      A string describing how spot ROIs should be displayed
    :returns:       The n. of detected spots
    """
    settings = Settings()
    settings.setFrom(imp)
    settings.detectorFactory = (LogDetectorFactory() if "LoG" in detector_type
                                else DogDetectorFactory())
    settings.detectorSettings = {
        DK.KEY_DO_SUBPIXEL_LOCALIZATION: False,
        DK.KEY_DO_MEDIAN_FILTERING: True,
        DK.KEY_TARGET_CHANNEL: channel,
        DK.KEY_RADIUS: radius,
        DK.KEY_THRESHOLD: threshold,
    }
    trackmate = TrackMate(settings)
    if not trackmate.execDetection():
        lservice.error(str(trackmate.getErrorMessage()))
        return 0
    model = trackmate.model
    spots = model.getSpots()
    count = spots.getNSpots(False)
    ch_id = "Spots Ch%d" % channel
    if count > 0:
        roi = None
        cal = imp.getCalibration()
        t_pos = imp.getT()
        if (t_pos > 1):
            lservice.warn("Only frame %d was considered..." % t_pos)
        for spot in spots.iterable(False):
            x = cal.getRawX(spot.getFeature(spot.POSITION_X))
            y = cal.getRawY(spot.getFeature(spot.POSITION_Y))
            z = spot.getFeature(spot.POSITION_Z)
            if z == 0 or not cal.pixelDepth or cal.pixelDepth == 0:
                z = 1
            else:
                z = int(z // cal.pixelDepth)
            imp.setPosition(channel, z, t_pos)
            if roi is None:
                roi = PointRoi(int(x), int(y), imp)
            else:
                roi.addPoint(imp, x, y)
        roi.setStrokeColor(colorRGBtoColor(roi_color))
        if "large" in roi_type:
            roi.setPointType(3)
            roi.setSize(4)
        else:
            roi.setPointType(2)
            roi.setSize(1)
        overlay.add(roi, ch_id)
    return count
               for i in range(img.numDimensions())]  # no calibration: identity
sigmaSmaller = 15  # in pixels: a quarter of the radius of an embryo
sigmaLarger = 30  # pixels: half the radius of an embryo
extremaType = DogDetection.ExtremaType.MAXIMA
minPeakValue = 10
normalizedMinPeakValue = False

# In the differece of gaussian peak detection, the img acts as the interval
# within which to look for peaks. The processing is done on the infinite imgE.
dog = DogDetection(imgE, img, calibration, sigmaSmaller, sigmaLarger,
                   extremaType, minPeakValue, normalizedMinPeakValue)

peaks = dog.getSubpixelPeaks()

# Create a PointRoi from the DoG peaks, for visualization
roi = PointRoi(0, 0)
# A temporary array of integers, one per dimension the image has
p = zeros(img.numDimensions(), 'd')
# Load every peak as a point in the PointRoi
for peak in peaks:
    # Read peak coordinates into an array of integers
    peak.localize(p)
    roi.addPoint(imp, int(p[0]), int(p[1]))

imp.setRoi(roi)

# Now, iterate each peak, defining a small interval centered at each peak,
# and measure the sum of total pixel intensity,
# and display the results in an ImageJ ResultTable.
table = ResultsTable()
Beispiel #30
0
    One = Scalar(1.0)
    CorrMapInvCV = subtract(One, CorrMapCV).asMat()
    #CorrMapInv = MatToImProc(CorrMapInvCV)
    #CorrMapInv = ImagePlus("Inverted", CorrMapInv)
    #CorrMapInv.show()

    # Apply a "TO ZERO" threshold on the correlation map : to compensate the fact that maxima finder does not have a threshold argument
    # TO ZERO : below the threshold set to 0, above left untouched
    # NB : 1-score_threshold since we have inverted the image : we want to look for minima of value <x so we have to look for maxima of value>1-x in the inverted image
    CorrMapThreshCV = Mat()
    threshold(CorrMapInvCV, CorrMapThreshCV, 1 - score_threshold, 0,
              CV_THRESH_TOZERO)
    #CorrMapThreshImp = ImagePlus("Thresholded", CorrMapThresh)
    #CorrMapThreshImp.show()

else:
    CorrMapThreshCV = Mat()
    threshold(CorrMapCV, CorrMapThreshCV, score_threshold, 0, CV_THRESH_TOZERO)

# Display
CorrMapThresh = MatToImProc(
    CorrMapThreshCV)  # Keep this conversion, not only for visualisation
CorrMapThreshImp = ImagePlus("Score Map - thresholded", CorrMapThresh)
CorrMapThreshImp.show()

## For both cases (Multi-Min/Max-detection) detect maxima on the thresholded map
excludeOnEdge = False  # otherwise miss quite a lot of them
tolerance = 0
Polygon = MaximumFinder().getMaxima(CorrMapThresh, tolerance, excludeOnEdge)
roi = PointRoi(Polygon)
CorrMapThreshImp.setRoi(roi)
 def updatePointRoi(self):
     # Surround with try/except to prevent blocking
     #   ImageJ's stack slice updater thread in case of error.
     try:
         # Update PointRoi
         self.imp.killRoi()
         points = self.nuclei[
             self.imp.getSlice() -
             1]  # map 1-based slices to 0-based nuclei Z coords
         if 0 == len(points):
             IJ.log("No points for slice " + str(self.imp.getSlice()))
             return
         roi = PointRoi()
         # Style: large, red dots
         roi.setSize(4)  # ranges 1-4
         roi.setPointType(2)  # 2 is a dot (filled circle)
         roi.setFillColor(Color.red)
         roi.setStrokeColor(Color.red)
         # Add points
         for point in points:  # points are floats
             roi.addPoint(self.imp, int(point[0]), int(point[1]))
         self.imp.setRoi(roi)
     except:
         IJ.error(sys.exc_info())
Beispiel #32
0
def draw_centers(data):
    pathname = data[1]
    filename = data[2]
    platename = data[3]

    print data[4]
    nx = int(data[4])
    ny = int(data[5])
    nx_com = int(data[6])
    ny_com = int(data[7])
    ax = int(data[8])
    ay = int(data[9])
    
    orientation = 2*math.pi * float(data[10]) / 360.0
    line_dy = int(round(math.atan(orientation) * LINE_DX))
    ax2 = ax - LINE_DX
    ay2 = ay - line_dy

    orientation_avg = 2*math.pi * float(data[11]) / 360.0
    line_dy = int(round(math.atan(orientation_avg) * LINE_DX))
    ax3 = ax - LINE_DX
    ay3 = ay - line_dy

    imp = IJ.openImage(os.path.join(pathname,filename))

    roi_nucleus = PointRoi(nx,ny)
    roi_nucleus.setDefaultMarkerSize("Large")
    roi_nucleus.setStrokeColor(Color.CYAN)
    roi_nucleus_com = PointRoi(nx_com,ny_com)
    roi_nucleus_com.setDefaultMarkerSize("Large")
    roi_nucleus_com.setStrokeColor(Color.GREEN)
    roi_anchor = PointRoi(ax,ay)
    roi_anchor.setDefaultMarkerSize("Large")
 
    imp.getProcessor().drawRoi(roi_nucleus)
    imp.getProcessor().drawRoi(roi_nucleus_com)
    imp.getProcessor().drawRoi(roi_anchor)

    imp.setColor(Color.RED)
    imp.getProcessor().drawLine(ax,ay,ax2,ay2)
    imp.setColor(Color.WHITE)
    imp.getProcessor().drawLine(ax,ay,ax3,ay3)


    IJ.saveAsTiff(imp,os.path.join(pathname,filename))
Beispiel #33
0
def processOneImage(inputDir):
    tmp = glob.glob(os.path.join(inputDir, "fibrone*"))
    fibronectin = tmp[0]
    tmp = glob.glob(os.path.join(inputDir, "nucleus*"))
    nucleus = tmp[0]
    tmp = glob.glob(os.path.join(inputDir, "actin*"))
    actin = tmp[0]
    
    # read sample name
    head,tail = os.path.split(inputDir)
    sample = tail.replace(".tif_Files","")

    # original images
    imp_fn_orig = IJ.openImage(fibronectin)
    imp_nuc_orig = IJ.openImage(nucleus)

    # work copies
    imp_fn = imp_fn_orig.duplicate()
    imp_nuc = imp_nuc_orig.duplicate()

    IJ.run(imp_fn,"Set Scale...", "distance=1 known=1 pixel=1 unit=pixels")
    IJ.run(imp_fn,"Gaussian Blur...","sigma=5")
    IJ.run(imp_fn,"Make Binary","")
    IJ.run(imp_nuc,"Set Scale...", "distance=1 known=1 pixel=1 unit=pixels")
    IJ.run(imp_nuc,"Gaussian Blur...","sigma=5")
    IJ.run(imp_nuc,"Make Binary","")

    # get moments of the fibronectin image
    moments_file = os.path.join(OUTPUT, sample + " moments.txt")
    printMoments(fibronectin, moments_file)
    moments = readMoments(moments_file)
    print moments.m00
    sys.exit()

    # centroid of fibronectin anchor
    centers = getParticleCenters(imp_fn)
    cxfn = int(round(centers[0][0]))
    cyfn = int(round(centers[1][0]))
    fn_centroid_roi = PointRoi(cxfn,cyfn)
    fn_centroid_roi.setDefaultMarkerSize("Large")
    fn_centroid_roi.setStrokeColor(Color.CYAN)

    # center of mass of nucleus 
    centers = getParticleCenters(imp_nuc)
    cxnuc = int(round(centers[2][0]))
    cynuc = int(round(centers[3][0]))
    nuc_com_roi = PointRoi(cxnuc,cynuc)
    nuc_com_roi.setDefaultMarkerSize("Large")

    # skeletonize fibronectin anchor to find its orientation
    IJ.run(imp_fn,"Skeletonize","")
    skel = AnalyzeSkeleton_()
    skel.setup("",imp_fn)
    skelResult = skel.run(skel.NONE, False, True, None, True, True)
    graph = skelResult.getGraph()
    print len(graph)
    print skelResult.getNumOfTrees()
    # find the longest graph
    graph = sorted(graph, key=lambda g: getGraphLength(g), reverse=True)
    graph = graph[0]
    edges = graph.getEdges()
    # find longest edge, the main axis of the anchor
    edges = sorted(edges, key=lambda edge: edge.getLength(), reverse=True)
    #for e in edges:
    #    print e.getLength()
    v1long = edges[0].getV1()
    v2long = edges[0].getV2()
    x1 = v1long.getPoints()[0].x
    y1 = v1long.getPoints()[0].y
    x2 = v2long.getPoints()[0].x
    y2 = v2long.getPoints()[0].y
    anchor_roi = PointRoi(x1,y1)
    anchor_roi = anchor_roi.addPoint(x2,y2)
    # find top and bottom vertices of the graph
    vertices = graph.getVertices()
    vertices = sorted(vertices, key=lambda vertex: vertex.getPoints()[0].y)
    v1short = vertices[len(vertices)-1]
    v2short = vertices[0]
    x3 = v1short.getPoints()[0].x
    y3 = v1short.getPoints()[0].y
    x4 = v2short.getPoints()[0].x
    y4 = v2short.getPoints()[0].y
    anchor_roi = anchor_roi.addPoint(x3,y3)
    anchor_roi = anchor_roi.addPoint(x4,y4)
    # calculate angles
    a1 = math.atan(abs(float(y2-y1)/float(x2-x1))) / math.pi * 360
    a2 = math.atan(abs(float(x4-x3)/float(y4-y3))) / math.pi * 360
    amean = float((a1+a2)/2)
    dx = cxfn-cxnuc
    print sample,cxfn,cyfn,cxnuc,cynuc,dx,math.cos(amean)*dx,x1,y1,x2,y2,x3,y3,x4,y4,a1,a2

    # create composite
    comp = ImagePlus("composite",imp_nuc_orig.getProcessor().convertToColorProcessor())
    comp.getProcessor().setChannel(2,imp_fn_orig.getProcessor())
    comp.getProcessor().setChannel(3,imp_fn.getProcessor())
    comp.show()
    comp.getProcessor().drawRoi(fn_centroid_roi)
    comp.getProcessor().drawRoi(nuc_com_roi)
    comp.getProcessor().drawRoi(anchor_roi)
    comp.repaintWindow()
    IJ.saveAsTiff(comp, os.path.join(OUTPUT,sample + ".tif"))
Beispiel #34
0
print("%i regions/particles detected" % len(region_labels))

# Now use IJ1 RoiManager to display the detected regions
rm = get_roi_manager(new=True)

for label in region_labels:

    region = regions.getLabelRegion(label)

    # Get the center of mass of the region
    center = region.getCenterOfMass()
    x = center.getDoublePosition(0)
    y = center.getDoublePosition(1)

    roi = PointRoi(x, y)
    if center.numDimensions() >= 3:
        z = center.getDoublePosition(2)
        roi.setPosition(int(z))

    rm.addRoi(roi)

    # You can also iterate over the `data` pixel by LabelRegion

    cursor = region.localizingCursor()
    dataRA = data.randomAccess()
    while cursor.hasNext():
        cursor.fwd()
        dataRA.setPosition(cursor)

        x = cursor.getDoublePosition(0)
Beispiel #35
0
	xmlfile = arg[0]
	ch = 1

#open xml file and parse it
tree = ET.parse(xmlfile)
root = tree.getroot()
obj, imgName = getPosition(root)
print imgName

#open image
img =  BF.openImagePlus(imgName)[0] 
img.setZ(obj[1][2]+1)
img.setC(int(ch))
img.show()


#draw rois
for i in range(1, len(obj)+1):
	PR = PointRoi(obj[i][0],obj[i][1])
	try:
		PR.setSize(3)
		PR.setPointType(0)
		roim.addRoi(PR)
	except:
		roim.addRoi(PR)

roim.runCommand('Show All with Labels')



 
print("%i regions/particles detected" % len(region_labels))
 
# Now use IJ1 RoiManager to display the detected regions 
rm = get_roi_manager(new=True)

for label in region_labels:
  
    region = regions.getLabelRegion(label)

  	# Get the center of mass of the region
    center = region.getCenterOfMass()
    x = center.getDoublePosition(0)
    y = center.getDoublePosition(1)
  
    roi = PointRoi(x, y)
    if center.numDimensions() >= 3:
        z = center.getDoublePosition(2)
        roi.setPosition(int(z))
      
    rm.addRoi(roi)
 
    # You can also iterate over the `data` pixel by LabelRegion
 
    cursor = region.localizingCursor()
    dataRA = data.randomAccess()
    while cursor.hasNext():
        cursor.fwd()
        dataRA.setPosition(cursor)
     
        x = cursor.getDoublePosition(0)
Beispiel #37
0
def run():

	IJ.run("Close All", "")
	IJ.log("\\Clear")

	IJ.log("Find_close_peaks")

	imp = IJ.run("Bio-Formats Importer")
	imp = IJ.getImage()


	Channel_1, Channel_2, radius_background, sigmaSmaller, sigmaLarger, minPeakValue, min_dist = getOptions()

	IJ.log("option used:" \
    		+ "\n" + "channel 1:" + str(Channel_1) \
    		+ "\n" + "channel 2:"+ str(Channel_2) \
    		+ "\n" + "Radius Background:"+ str(radius_background) \
    		+ "\n" + "Smaller Sigma:"+ str(sigmaSmaller) \
    		+ "\n" + "Larger Sigma:"+str(sigmaLarger) \
    		+ "\n" + "Min Peak Value:"+str(minPeakValue) \
    		+ "\n" + "Min dist between peaks:"+str(min_dist))

	IJ.log("Computing Max Intensity Projection")

	if imp.getDimensions()[3] > 1:
		imp_max = ZProjector.run(imp,"max")
		#imp_max = IJ.run("Z Project...", "projection=[Max Intensity]")
		#imp_max = IJ.getImage()
	else:
		imp_max = imp

	ip1, ip2 = extract_channel(imp_max, Channel_1, Channel_2)
	imp1, imp2 = back_substraction(ip1, ip2, radius_background)
	imp1.show()
	imp2.show()

	IJ.log("Finding Peaks")

	ip1_1, ip2_1, peaks_1, peaks_2 = find_peaks(imp1, imp2, sigmaSmaller, sigmaLarger, minPeakValue)

	# Create a PointRoi from the DoG peaks, for visualization
	roi_1 = PointRoi(0, 0)
	roi_2 = PointRoi(0, 0)
	roi_3 = PointRoi(0, 0)
	roi_4 = PointRoi(0, 0)

	# A temporary array of integers, one per dimension the image has
	p_1 = zeros(ip1_1.numDimensions(), 'i')
	p_2 = zeros(ip2_1.numDimensions(), 'i')

	# Load every peak as a point in the PointRoi
	for peak in peaks_1:
	  # Read peak coordinates into an array of integers
	  peak.localize(p_1)
	  roi_1.addPoint(imp1, p_1[0], p_1[1])

	for peak in peaks_2:
	  # Read peak coordinates into an array of integers
	  peak.localize(p_2)
	  roi_2.addPoint(imp2, p_2[0], p_2[1])

	# Chose minimum distance in pixel
	#min_dist = 20

	for peak_1 in peaks_1:
		peak_1.localize(p_1)
		for peak_2 in peaks_2:
			peak_2.localize(p_2)
			d1 = distance(p_1, p_2)
			if  d1 < min_dist:
				roi_3.addPoint(imp1, p_2[0], p_2[1])
				break

	for peak_2 in peaks_2:
		peak_2.localize(p_2)
		for peak_1 in peaks_1:
			peak_1.localize(p_1)
			d2 = distance(p_2, p_1)
			if  d2 < min_dist:
				roi_4.addPoint(imp1, p_2[0], p_2[1])
				break

	rm = RoiManager.getInstance()
	if not rm:
	  rm = RoiManager()
	rm.reset()

	rm.addRoi(roi_1)
	rm.addRoi(roi_2)
	rm.addRoi(roi_3)
	rm.addRoi(roi_4)

	rm.select(0)
	rm.rename(0, "ROI neuron")
	rm.runCommand("Set Color", "yellow")

	rm.select(1)
	rm.rename(1, "ROI glioma")
	rm.runCommand("Set Color", "blue")

	rm.select(2)
	rm.rename(2, "ROI glioma touching neurons")
	rm.runCommand("Set Color", "red")

	rm.select(3)
	rm.rename(3, "ROI neurons touching glioma")
	rm.runCommand("Set Color", "green")

	rm.runCommand(imp1, "Show All")

	#Change distance to be in um
	cal = imp.getCalibration()
	min_distance = str(round((cal.pixelWidth * min_dist),1))

	table = ResultsTable()
	table.incrementCounter()
	table.addValue("Numbers of Neuron Markers", roi_1.getCount(0))
	table.addValue("Numbers of Glioma Markers", roi_2.getCount(0))
	table.addValue("Numbers of Glioma within %s um of Neurons" %(min_distance), roi_3.getCount(0))
	table.addValue("Numbers of Neurons within %s um of Glioma" %(min_distance), roi_4.getCount(0))

	table.show("Results Analysis")