コード例 #1
0
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()
コード例 #2
0
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()
コード例 #3
0
def getCells(dicStack):
    outStack = ImageStack(W,H)

    cells = [None for t in range(T+1)]

    for t in range(1,T+1):
        mapp = dicStack.getProcessor(t).convertToFloatProcessor()

        mapp.subtract( mapp.getStatistics().mean )
        mapp.abs()

        RankFilters().rank(mapp, 1.0, RankFilters.VARIANCE)
        mapp.sqrt()

        mapp.blurGaussian(5)

        hist = mapp.getHistogram(256)
        stats = mapp.getStatistics()

        thresh = AutoThresholder().getThreshold( AutoThresholder.Method.Otsu, hist )
        thresh = (thresh/float(255)) * (stats.max-stats.min) + stats.min

        mask = ByteProcessor(W,H)
        for i in range(W*H):
            value = mapp.getf(i)
            bite = 255 if value>=thresh else 0
            mask.set(i, bite)

        fillHoles(mask)
        ed = 3
        for e in range(ed): mask.erode(1, 0)
        for d in range(ed): mask.dilate(1, 0)

        watershed(mask)

        minA = 5000 #px²

        mask.setThreshold(255,255, ImageProcessor.NO_LUT_UPDATE)
        composite = ThresholdToSelection().convert(mask)

        rois = ShapeRoi(composite).getRois()
        keep = []
        for roi in rois:
            if roi.getStatistics().area >= minA:
                if not onEdge(roi):
                    keep.append(roi)
                else:
                    edgeRoi = ShapeRoi(roi)
                    edgeRoi.setPosition(0,0,t)
                    edgeRoi.setStrokeColor(Color.YELLOW)
                    ol.add(edgeRoi)
        print("T"+str(t)+" using "+str(len(keep))+"/"+str(len(rois))+" ROIs")
        rois = keep
        #rois = [ roi for roi in rois if roi.getStatistics().area >= minA and not onEdge(roi) ]	#keep big enough and not on edges

        # if there is only one Roi, cut it along the fitted ellipse minor axis
        if len(rois)==1:
            el = EllipseFitter()
            mask.setRoi(rois[0])
            el.fit(mask, None)
            el.makeRoi(mask)
            theta = el.angle * (maths.pi/180.0)

            length = el.major/2.0
            dy = maths.sin(theta)* length
            dx = maths.cos(theta)* length

            #major axis
            lineX0 = el.xCenter - dx
            lineY0 = el.yCenter + dy
            lineX1 = el.xCenter + dx
            lineY1 = el.yCenter - dy
            line = Line(lineX0, lineY0, lineX1, lineY1)
            line.setStrokeColor(Color.BLUE)
            line.setStrokeWidth(1)
            line.setPosition(0,0,t)
            ol.add(line)

            #minor axis scaled length to make sure cut ends are outside Roi
            cutX0 = el.xCenter + dy*100
            cutY0 = el.xCenter + dx*100
            cutX1 = el.yCenter - dy*100
            cutY1 = el.yCenter - dx*100

            cut = Line(cutX0,cutY0, cutX1, cutY1)
            cut.setStrokeWidth(2)
            cut = PolygonRoi( cut.getFloatPolygon(), PolygonRoi.POLYGON )

            mask.setColor(0)
            mask.fill(cut)
            composite = ThresholdToSelection().convert(mask)

            rois = ShapeRoi(composite).getRois()
            rois = [ roi for roi in rois if roi.getStatistics().area >= minA ]
        print(str(t) + ":" + str(len(rois)))

        rois = [ PolygonRoi(roi.getInterpolatedPolygon(20, True), PolygonRoi.POLYGON) for roi in rois ]
        rois = [ PolygonRoi(roi.getConvexHull(), PolygonRoi.POLYGON) for roi in rois ]

        rois = sorted(list(rois), key=lambda roi:roi.getLength() )	#size order
        rois = rois[-2:]											#keep 2 biggest
        rois = sorted(list(rois), key=lambda roi:roi.getStatistics().xCentroid+roi.getStatistics().yCentroid )	#top left to bottom right order

        if len(rois)>0:
            rois[0].setStrokeColor(Color.RED)
            rois[0].setPosition(0, 0, t)
            ol.add(rois[0])
        if len(rois)>1:
            rois[1].setStrokeColor(Color.GREEN)
            rois[1].setPosition(0, 0, t)
            ol.add(rois[1])
            cells[t] = (rois[0], rois[1])


    return cells
コード例 #4
0
ファイル: MorphoBact.py プロジェクト: leec13/MorphoBactPy
	def __midline(self):
		debug=False
		#print "line 251", self.__boolML
		if self.__boolML :
			ordpoints=self.__midLine[:]
			npoints=len(ordpoints)
			xpoints=[point[0] for point in ordpoints]
			ypoints=[point[1] for point in ordpoints]
			polyOrd=PolygonRoi(xpoints, ypoints, npoints, PolygonRoi.POLYLINE)
			return polyOrd

		#if self.getMaxF()<15 : return None
			#self.__FeretAxis()
			#return self.__line

		self.__boolML=True
		self.__image.killRoi()
		self.__image.setRoi(self.__contour)
		boundRect=self.__contour.getBounds()
		boundRoi=Roi(boundRect)
		xori=boundRect.x
		yori=boundRect.y
		wori=boundRect.width
		hori=boundRect.height
		ip2 = ByteProcessor(self.__image.getWidth(), self.__image.getHeight())
		ip2.setColor(255)
		ip2.setRoi(self.__contour)
		ip2.fill(self.__contour)
		skmp=ImagePlus("ip2", ip2)
		skmp.setRoi(xori-1,yori-1,wori+1,hori+1)
		ip3=ip2.crop()
		skmp3=ImagePlus("ip3", ip3)
		skmp3.killRoi()
		#-------------------------------------------------------------
		if debug : 
			skmp3.show()
			IJ.showMessage("imp3 l287")
		#-------------------------------------------------------------
		IJ.run(skmp3, "Skeletonize (2D/3D)", "")
		#IJ.run(skmp3, "Skeletonize", "")
		#-------------------------------------------------------------
		if debug : 
			skmp3.show()
			IJ.showMessage("imp3 l294")
		#-------------------------------------------------------------
		IJ.run(skmp3, "BinaryConnectivity ", "white")
		ip3.setThreshold(3,4, ImageProcessor.BLACK_AND_WHITE_LUT)
		IJ.run(skmp3, "Convert to Mask", "")
		#-------------------------------------------------------------
		if debug : 
			skmp3.show()
			IJ.showMessage("imp3 l302")
		#-------------------------------------------------------------
		#IJ.run(skmp3, "Skeletonize", "")
		#-------------------------------------------------------------
		if debug : 
			skmp3.updateAndDraw() 
			skmp3.show()
			IJ.showMessage("imp3 l308")
		#-------------------------------------------------------------
		rawPoints=[]
		w=ip3.getWidth()
		h=ip3.getHeight()
		
		rawPoints=[(x+xori,y+yori,self.__sommeVals(x,y,ip3)) for x in range(w) for y in range(h) if ip3.getPixel(x,y)==255]
		tempbouts=[val for val in rawPoints if val[2]==2]

		if len(tempbouts)!=2 : return None
		# test
		#if len(tempbouts)!=2 :
		#	
		#	IJ.run(skmp3, "BinaryConnectivity ", "white")
		#	ip3.setThreshold(3,3, ImageProcessor.BLACK_AND_WHITE_LUT)
		#	IJ.run(skmp3, "Convert to Mask", "")
		#	#-------------------------------------------------------------
		#	if debug==debug : 
		#		skmp3.updateAndDraw() 
		#		skmp3.show()
		#		IJ.showMessage("if test l 328")
		##-------------------------------------------------------------
		#	rawPoints=[(x+xori,y+yori,self.__sommeVals(x,y,ip3)) for x in range(w) for y in range(h) if ip3.getPixel(x,y)==255]
		#	tempbouts=[val for val in rawPoints if val[2]==2]
			
		ip3.setRoi(boundRect)
		if rawPoints==[]: return None
		npoints=len(rawPoints)
		xpoints=[point[0] for point in rawPoints]
		ypoints=[point[1] for point in rawPoints]
		valpoints=[point[2] for point in rawPoints]
		
		bouts={}
		
		if tempbouts==[]: return None
		
		if tempbouts[0][1]>tempbouts[1][1]:
			bouts["A"]=tempbouts[0]
			bouts["B"]=tempbouts[1]
		else:
			bouts["A"]=tempbouts[1]
			bouts["B"]=tempbouts[0]

		rawPoints.remove(bouts["A"])

		rawPoints.remove(bouts["B"])
		rawPoints.append(bouts["B"])

		tempList=[val for val in rawPoints]

		p=bouts["A"]
		Dist={}
		ordPoints=[]
		
		for j in range(len(rawPoints)):
			Dist.clear()
			for i in range(len(tempList)):
				dx=p[0]-tempList[i][0]
				dy=p[1]-tempList[i][1]
				d=math.sqrt(dx*dx+dy*dy)
				Dist[d]=tempList[i]

			distList=Dist.keys()
			mind=min(distList)
			nextpoint=Dist[mind]
			ordPoints.append(nextpoint)
			tempList.remove(nextpoint)
			p=nextpoint

		ordPoints.insert(0, bouts["A"])
		
		npoints=len(ordPoints)
		if npoints < 4 : return None
		xpoints=[point[0] for point in ordPoints]
		ypoints=[point[1] for point in ordPoints]
		polyOrd1=PolygonRoi(xpoints, ypoints, npoints, PolygonRoi.POLYLINE)
		
		f=min(self.__midParams[0], len(xpoints)//2)
		
		angleA1=polyOrd1.getAngle(xpoints[0],ypoints[0], xpoints[1],ypoints[1])
		angleA2=polyOrd1.getAngle(xpoints[1],ypoints[1], xpoints[2],ypoints[3])
		angleA = (angleA1+angleA2)/2.00
		angleA=polyOrd1.getAngle(xpoints[0],ypoints[0], xpoints[f],ypoints[f])
		angleA=angleA*(math.pi/180)
		
		angleB1=polyOrd1.getAngle(xpoints[-2],ypoints[-2], xpoints[-1],ypoints[-1])
		angleB2=polyOrd1.getAngle(xpoints[-3],ypoints[-3], xpoints[-2],ypoints[-2])
		angleB = (angleB1+angleB2)/2.00
		angleB=polyOrd1.getAngle(xpoints[-f],ypoints[-f], xpoints[-1],ypoints[-1])
		angleB=angleB*(math.pi/180)

		coef=self.__midParams[1]
		
		xa = xpoints[0]-coef*f*math.cos(angleA)
		ya = ypoints[0]+coef*f*math.sin(angleA)
		xb = xpoints[-1]+coef*f*math.cos(angleB)
		yb = ypoints[-1]-coef*f*math.sin(angleB)

		lineA=Line(xpoints[0],ypoints[0], xa, ya)
		lineB=Line(xpoints[-1],ypoints[-1], xb, yb)
		lineA.setWidth(0)
		lineB.setWidth(0)
		lineA.setStrokeWidth(0) 
		lineB.setStrokeWidth(0)
		
		ip2.setColor(0)
		ip2.fill()
		ip2.setColor(255)
		ip2.setRoi(lineA)
		lineA.drawPixels(ip2)
		ip2.setRoi(lineB)
		lineB.drawPixels(ip2)

		ip2.setRoi(self.__contour)
		ip2.setColor(0)
		ip2.fillOutside(self.__contour)
		ip2=ip2.crop()
		imb=ImagePlus("new-ip2", ip2)
				
		#-------------------------------------------------------------
		if debug : 
			imb.show()
			IJ.showMessage("imb l416")
		#-------------------------------------------------------------
		w2=ip2.getWidth()
		h2=ip2.getHeight()
		ip4 = ByteProcessor(w2+2, h2+2)
		im4=ImagePlus("im4", ip4)

		for i in range(w2):
			for j in range(h2):
				ip4.set(i+1,j+1,max([ip2.getPixel(i,j),ip3.getPixel(i,j)]))
		#im4.show()
		#-------------------------------------------------------------
		if debug : 
			im4.show()
			IJ.showMessage("im4 l430")
		#-------------------------------------------------------------
		im4.killRoi()
		#IJ.run(im4, "Skeletonize (2D/3D)", "")
		#IJ.run(skmp3, "Skeletonize", "")
		#-------------------------------------------------------------
		if debug : 
			imb.show()
			IJ.showMessage("imb l300")
		#-------------------------------------------------------------
		#IJ.run(skmp3, "Skeletonize", "")
		ip4=im4.getProcessor()
		
		rawPoints2=[]
		w4=ip4.getWidth()
		h4=ip4.getHeight()
		

		rawPoints2=[(x+xori-2,y+yori-2,self.__sommeVals(x,y,ip4)) for x in range(w4) for y in range(h4) if ip4.getPixel(x,y)==255]
		self.__MidBouts=[val for val in rawPoints2 if val[2]==2]

		# test
		if len(self.__MidBouts)!=2 : 
			IJ.run(im4, "BinaryConnectivity ", "white")
			ip4.setThreshold(3,3, ImageProcessor.BLACK_AND_WHITE_LUT)
			IJ.run(im4, "Convert to Mask", "")
			rawPoints2=[(x+xori-2,y+yori-2,self.__sommeVals(x,y,ip4)) for x in range(w4) for y in range(h4) if ip4.getPixel(x,y)==255]
			self.__MidBouts=[val for val in rawPoints2 if val[2]==2]
		
		ordpoints=[]
		p0=self.__MidBouts[0]
		rawPoints2.remove(p0)
		c=0
		
		while p0!=self.__MidBouts[1]:
			if c<len(rawPoints2):
				point=rawPoints2[c]
			else: break
			if abs(point[0]-p0[0])<2 and abs(point[1]-p0[1])<2:
				p0=point
				ordpoints.append(point)
				rawPoints2.remove(point)
				c=0
			else: c=c+1

		ordpoints.insert(0, self.__MidBouts[0])
		self.__midLine=ordpoints[:]
		self.__midCenters = self.__Centers(self.__midLine)
		npoints=len(ordpoints)
		xpoints=[point[0] for point in ordpoints]
		ypoints=[point[1] for point in ordpoints]

		polyOrd=PolygonRoi(xpoints, ypoints, npoints, PolygonRoi.POLYLINE)

		
		#print self.__midLine
		#print self.__MidBouts
		#print xpoints
		#print ypoints

		return polyOrd
コード例 #5
0
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)