Beispiel #1
0
	def __FeretAxis(self):

		__boolFL=True
		if (self.__contour is not None) and (self.__contour.getType() in range(1,11)):
			self.__image.killRoi()
			self.__image.setRoi(self.__contour)
			if self.__contour.getType() in [1,5,9,10]:
				self.__polygon=self.__contour.getPolygon()
			else:
				self.__polygon=self.__contour.getFloatPolygon()
			points = self.__polygon.npoints
			self.__polx = self.__polygon.xpoints
			self.__poly = self.__polygon.ypoints
			diameter=0.0
			for i in range(points):
				for j in range(i, points):
					dx=self.__polx[i]-self.__polx[j]
					dy=self.__poly[i]-self.__poly[j]
					d=math.sqrt(dx*dx+dy*dy)
					if d>diameter:
						diameter=d
						i1=i
						i2=j
			
			tempDictY={ self.__poly[i1]:(self.__polx[i1],self.__poly[i1],self.__polx[i2],self.__poly[i2]), self.__poly[i2]:(self.__polx[i2],self.__poly[i2],self.__polx[i1],self.__poly[i1]) }			
			
			minY=min((self.__poly[i1],self.__poly[i2]))
			maxY=max((self.__poly[i1],self.__poly[i2]))
			lineTuple=tempDictY[maxY]
			
			self.__x1=lineTuple[0]
			self.__y1=lineTuple[1]
			self.__x2=lineTuple[2]
			self.__y2=lineTuple[3]
			
			self.__line= Line(self.__x1,self.__y1,self.__x2,self.__y2)			
			
			
		elif (self.__contour is not None) and (self.__contour.getType()==0):
			self.__x2=self.__contour.getBounds().x
			self.__y2=self.__contour.getBounds().y
			self.__x1=self.__contour.getBounds().x+self.__contour.getBounds().width
			self.__y1=self.__contour.getBounds().y+self.__contour.getBounds().height
			self.__line= Line(self.__x1,self.__y1,self.__x2,self.__y2)


		else:
			self.__x1="NaN"
			self.__y1="NaN"
			self.__x2="NaN"
			self.__y2="NaN"
			self.__fprofArray="NaN"
def 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 #3
0
def draw_scale(image, ticks):
    cal = image.getCalibration()
    overlay = Overlay()
    image.setOverlay(overlay)
    TextRoi.setGlobalJustification(TextRoi.CENTER)
    offset = image.getHeight() - extend
    for tick in ticks:
        tick_pos = cal.getRawX(tick)
        line = Line(tick_pos, offset, tick_pos, offset + font_size)
        line.setWidth(font_size // 8)
        line.setStrokeColor(Color(1.00, 1.00, 1.00))
        overlay.add(line)
        text = TextRoi(tick_pos, offset + font_size, str(tick), font)
        text_width = text.getFloatWidth()
        text_y = text.getYBase()
        text.setLocation(tick_pos - text_width/2, text_y)
        text.setStrokeColor(Color(1.00, 1.00, 1.00))
        overlay.add(text)
Beispiel #4
0
 def generateOverlayRoi(self):
     """Generate the overlay ROI"""
     if (abs(self.p1[0] - self.p2[0])
         ) > 800:  # assume for now that lines run full length of image
         factor = 1024.0 / 800
         loresp1x = int(round(
             self.p1[0] / factor)) - self.referenceRoiOffsetXY[0]
         loresp1y = int(round(
             self.p1[1] / factor)) - self.referenceRoiOffsetXY[1]
         loresp2x = int(round(
             self.p2[0] / factor)) - self.referenceRoiOffsetXY[0]
         loresp2y = int(round(
             self.p2[1] / factor)) - self.referenceRoiOffsetXY[1]
         #print([(loresp1x, loresp1y), (loresp2x,loresp2y)]);
         return Line(loresp1x, loresp1y, loresp2x, loresp2y)
     else:
         return Line(self.p1[0] - self.referenceRoiOffsetXY[0],
                     self.p1[1] - self.referenceRoiOffsetXY[1],
                     self.p2[0] - self.referenceRoiOffsetXY[0],
                     self.p2[1] - self.referenceRoiOffsetXY[1])
Beispiel #5
0
	def getFeretSegments(self, n):
		self.__boolFS=True
		if(not self.__boolFL):
			self.__FeretAxis()
		radius=self.getMinF()
		lsegment=self.__line.getLength()/((n-1)*2)
		xo=self.__x1
		yo=self.__y1
		xf=self.__x2
		yf=self.__y2
		angle1=self.getAngF()*(math.pi/180)
		angle2=self.getAngF()*(math.pi/180)+(math.pi/2)
		avancex=(lsegment*2)*math.cos(angle1)
		avancey=(lsegment*2)*math.sin(angle1)
		delta90x=(radius)*math.cos(angle2)
		delta90y=(radius)*math.sin(angle2)
		self.__line.setWidth(int(lsegment*2))
		#self.__image.setRoi(self.__line)
		tempcontour=self.__contour.clone()
		shapeContour=ShapeRoi(tempcontour)
		segsRoi=[]
		for i in range(n):
			tempLine=Line(xo-delta90x, yo+delta90y, xo+delta90x, yo-delta90y)
			tempLine.setWidth(int(lsegment*2))
			poly=tempLine.getPolygon()
			roipol=PolygonRoi(poly, Roi.POLYGON)
			shapePoly= ShapeRoi(roipol)
			interShape=shapePoly.and(shapeContour)
			segsRoi.append(interShape.shapeToRoi())
			xo=xo+avancex
			yo=yo-avancey

		
		#self.__image.setRoi(self.__contour, True)
		#time.sleep(0)
		self.__line.setWidth(0)
		#self.__image.setRoi(tempcontour)
		
		#self.__image.updateAndDraw() 
		
		return segsRoi # return Roi array
Beispiel #6
0
	def __MidProfil(self):
		if not self.__boolML :  self.__midline()
		ip=self.__image.getProcessor()
		line=Line(self.__midLine[0][0],self.__midLine[0][1],self.__midLine[-1][0],self.__midLine[-1][1])
		line.setWidth(self.__lw)

		self.__MprofArray=[]
		self.__MprofArray[:]=[]
		for i in range(0,len(self.__midLine)-1):
			templine=Line(self.__midLine[i][0],self.__midLine[i][1],self.__midLine[i+1][0],self.__midLine[i+1][1])
			templine.setWidth(self.__lw)
			self.__image.setRoi(templine)
			#time.sleep(0.5)
			temprof= ProfilePlot(self.__image)
			temparray=temprof.getProfile()
			self.__MprofArray+=temparray
		templine.setWidth(0)
		#if self.__showMidpro: self.__fprof.createWindow()	 
		return
def 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 #8
0
class Morph(object):
	"""
		Fourni les mesures principales pour l'analyse des cellules bacteriennes:
		proprietes:
		1-MaxFeret
		2-MinFeret
		3-AngleFeret
		4-XFeret
		5-YFeret
		6-Area
		7-Mean
		8-StdDev
		9-IntDen
		10-Kurt
		11-Skew
		12-Angle
		13-Major
		14-Minor
		15-Solidity
		16-AR
		17-Round
		18-Circ.
		19-XM
		20-YM
		21-X
		22-Y
		23-FerCoord: tuple contenant x1, y1, x2, y2 du MaxFeret
		24-Fprofil: list contenant les valeurs du profil le long de MaxFeret
		25-FerAxis: Line ROI
		26-MidAxis: Polyline ROI de l'axe median par skeletonize
		27-MidProfil: list contenant les valeurs du profil le long de MidAxis
		28-nb Foci
		29-ListFoci: liste des positions des foci par cellule
		30-ListAreaFoci: liste des area des foci
		31-ListPeaksFoci: liste des int max des foci
		32-ListMeanFoci liste des int mean des foci
		
		toute les proprietes mettent a jour l'image cible par: object.propriete=imp
		
		Methodes:
		getFeretSegments(n segments)
		getMidSegments(n segments, radius, tool 0= ligne perpendiculaire, 1= cercle, 2= ligne tangente)
		selectInitRoi: active la ROI initiale
		
		Statics:
		distMorph(liste de coordonees a mesurer= (coefficient, valeur initiale, valeur finale))
		
		setteurs:
		setImage(ImagePlus)
		setImageMeasures(imagePlus) met a jours les mesures avec imagePlus
		setImageMidprofil(imagePlus) met a jours le profil avec imagePlus
		setLineWidth(width) afecte la largeur de ligne pour le profil pour Fprofile et MidProfil defaut = 0
		setshowFprof(True) affiche le graphique de profil Fprofil defaut = False
		setMidParams(longueur mesurer l'angle de l'extremite en pixels defaut=10, coefficient pour prolonger et trouver l'intersection avec le contour defaut=1.3
		
	"""

	def __Measures(self):

		self.__boolmeasures=True
		if (self.__contour is not None) and  (self.__contour.getType() not in [9,10]):
			self.__image.killRoi()
			self.__image.setRoi(self.__contour)
			self.__ip=self.__image.getProcessor()
			self.__rt= ResultsTable()
			analyser= Analyzer(self.__image, Analyzer.AREA+Analyzer.CENTER_OF_MASS+Analyzer.CENTROID+Analyzer.ELLIPSE+Analyzer.FERET+Analyzer.INTEGRATED_DENSITY+Analyzer.MEAN+Analyzer.KURTOSIS+Analyzer.SKEWNESS+Analyzer.MEDIAN+Analyzer.MIN_MAX+Analyzer.MODE+Analyzer.RECT+Analyzer.SHAPE_DESCRIPTORS+Analyzer.SLICE+Analyzer.STACK_POSITION+Analyzer.STD_DEV, self.__rt)
			analyser.measure()
			#self.__rt.show("myRT")
		else:
			self.__rt = ResultsTable()
			analyser = Analyzer(self.__image, Analyzer.AREA+Analyzer.CENTER_OF_MASS+Analyzer.CENTROID+Analyzer.ELLIPSE+Analyzer.FERET+Analyzer.INTEGRATED_DENSITY+Analyzer.MEAN+Analyzer.KURTOSIS+Analyzer.SKEWNESS+Analyzer.MEDIAN+Analyzer.MIN_MAX+Analyzer.MODE+Analyzer.RECT+Analyzer.SHAPE_DESCRIPTORS+Analyzer.SLICE+Analyzer.STACK_POSITION+Analyzer.STD_DEV, self.__rt)
			analyser.measure()
			#self.__rt.show("myRT")
			maxValues=self.__rt.getRowAsString(0).split("\t")
			heads=self.__rt.getColumnHeadings().split("\t")
			for val in heads: self.__rt.setValue(val, 0, Float.NaN)
			#self.__rt.show("myRT")

	# calculate the 1/2 , 1/4 ... 1/n positions for a liste while 1/n >= 1 returns a dict = 0: (0, [0, 0, pos(1/2)]) 1: (1, [-1, -0.5, -pos(1/4)], [0, 0, pos(1/2)], [1, 0.5, pos(1/2)])
	def __Centers(self, line) :
		L=len(line)
		l2=L//2
		l=L
		pos={}
		for i in range(self.log2(L)) : 
			l = l//2
			pos[i]=l
		l=L
		dicPos={}
		jtot=1
		for i in range(self.log2(L)) :
			s=[]
			j=1
			while (l2-j*pos[i])>0 or (l2+j*pos[i])<L :
				s.append((-j,(l2-j*pos[i])))
				s.append((j,(l2+j*pos[i])))
				j=j+1
			s.append((0,l2))
			s.sort()
			if ((len(s)+1)*pos[i]-L)//pos[i] > 0 :
				del s[0]
				del s[-1]

			else : pass
			if len(s) - 1  != 0 : jtot= (( len(s) - 1 ) / 2.00)+1
			else : jtot=1
			centers=[[v[0], v[0]/jtot, v[1]] for v in s]
			dicPos[i]=(i, centers)	
			del(s)
		return dicPos
		
	#calculate angle from the center of the midline to ends
	def __flexAngle(self) :
		try : 
			p1 = self.__midLine[0]
			p3 = self.__midLine[-1]
		except AttributeError : 
			self.__midline()
			p1 = self.__midLine[0]
			p3 = self.__midLine[-1]

		icenter = self.__midCenters[0][1][0][2]
		p2 = self.__midLine[icenter]
		#xpoints = (429,472,466)
		#ypoints = (114,133,99)
		xpoints = [int(p1[0]), int(p2[0]), int(p3[0])]
		ypoints = [int(p1[1]), int(p2[1]), int(p3[1])]
		#print ypoints
		#return ""
		r = PolygonRoi(xpoints, ypoints, 3, Roi.ANGLE)
		return r.getAngle()

	def __NbFoci(self):
		self.__boolFoci=True
		self.__image.killRoi()
		self.__image.setRoi(self.__contour)
		self.__ip=self.__image.getProcessor()
		rt=ResultsTable.getResultsTable()
		rt.reset()
		mf=MaximumFinder()
		mf.findMaxima(self.__ip, self.__noise, 0, MaximumFinder.LIST, True, False)
		self.__listMax[:]=[]
		
		#feret=self.getFercoord()
		#xc=feret[0]-((feret[0]-feret[2])/2.0)
		#yc=feret[1]-((feret[1]-feret[3])/2.0)

		#print xc, yc

		xc=self.getXC()
		yc=self.getYC()

		#print xc, yc
		
		for i in range(rt.getCounter()):
			x=int(rt.getValue("X", i))
			y=int(rt.getValue("Y", i))
			size=self.__localwand(x, y, self.__ip, self.__seuilPeaks, self.__peaksMethod, self.__light)
			coord=[(1, xc, x), (1, yc, y)]
 			d=self.distMorph(coord,"Euclidean distance")
 			d=( d / (self.getMaxF()/2) )*100
 			self.__listMax.append((x, y, size[0], size[1], size[2], size[3], size[4], d))
		rt.reset()
		
			
	def __FeretAxis(self):

		__boolFL=True
		if (self.__contour is not None) and (self.__contour.getType() in range(1,11)):
			self.__image.killRoi()
			self.__image.setRoi(self.__contour)
			if self.__contour.getType() in [1,5,9,10]:
				self.__polygon=self.__contour.getPolygon()
			else:
				self.__polygon=self.__contour.getFloatPolygon()
			points = self.__polygon.npoints
			self.__polx = self.__polygon.xpoints
			self.__poly = self.__polygon.ypoints
			diameter=0.0
			for i in range(points):
				for j in range(i, points):
					dx=self.__polx[i]-self.__polx[j]
					dy=self.__poly[i]-self.__poly[j]
					d=math.sqrt(dx*dx+dy*dy)
					if d>diameter:
						diameter=d
						i1=i
						i2=j
			
			tempDictY={ self.__poly[i1]:(self.__polx[i1],self.__poly[i1],self.__polx[i2],self.__poly[i2]), self.__poly[i2]:(self.__polx[i2],self.__poly[i2],self.__polx[i1],self.__poly[i1]) }			
			
			minY=min((self.__poly[i1],self.__poly[i2]))
			maxY=max((self.__poly[i1],self.__poly[i2]))
			lineTuple=tempDictY[maxY]
			
			self.__x1=lineTuple[0]
			self.__y1=lineTuple[1]
			self.__x2=lineTuple[2]
			self.__y2=lineTuple[3]
			
			self.__line= Line(self.__x1,self.__y1,self.__x2,self.__y2)			
			
			
		elif (self.__contour is not None) and (self.__contour.getType()==0):
			self.__x2=self.__contour.getBounds().x
			self.__y2=self.__contour.getBounds().y
			self.__x1=self.__contour.getBounds().x+self.__contour.getBounds().width
			self.__y1=self.__contour.getBounds().y+self.__contour.getBounds().height
			self.__line= Line(self.__x1,self.__y1,self.__x2,self.__y2)


		else:
			self.__x1="NaN"
			self.__y1="NaN"
			self.__x2="NaN"
			self.__y2="NaN"
			self.__fprofArray="NaN"
		
	def __FeretProfile(self):
		"""
			genere le profile le long du diametre de Feret
		"""
		self.__line.setWidth(self.__lw)
		self.__image.setRoi(self.__line, True)
		self.__fprof= ProfilePlot(self.__image)
		self.__fprofArray=self.__fprof.getProfile()
		if self.__showFpro: self.__fprof.createWindow()
		self.__image.killRoi()
		self.__line.setWidth(0)
		self.__image.setRoi(self.__contour)
		return self.__fprofArray
		
	def __midline(self):
		debug=False
		#print "line 251", self.__boolML
		if self.__boolML :
			ordpoints=self.__midLine[:]
			npoints=len(ordpoints)
			xpoints=[point[0] for point in ordpoints]
			ypoints=[point[1] for point in ordpoints]
			polyOrd=PolygonRoi(xpoints, ypoints, npoints, PolygonRoi.POLYLINE)
			return polyOrd

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

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

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

		rawPoints.remove(bouts["A"])

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

		tempList=[val for val in rawPoints]

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

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

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

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

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

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

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

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

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

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

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

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

		return polyOrd
		
	def __sommeVals(self, x, y, ip):

		return (ip.getPixel(x,y)+ip.getPixel(x-1,y-1)+ip.getPixel(x,y-1)+ip.getPixel(x+1,y-1)+ip.getPixel(x-1,y)+ip.getPixel(x+1,y)+ip.getPixel(x-1,y+1)+ip.getPixel(x,y+1)+ip.getPixel(x+1,y+1))/255

	def __localwand(self, x, y, ip, seuil, method, light):
		self.__image.killRoi()
		ip.snapshot()
		if method == "mean" : 
			peak=ip.getPixel(x,y)
			tol = (peak - self.getMean())*seuil
			w = Wand(ip)
			w.autoOutline(x, y, tol, Wand.EIGHT_CONNECTED)
			#print "method=", method, tol, peak
			
		elif method == "background" : 
			radius = self.getMinF()/4 
			bs = BackgroundSubtracter()
			#rollingBallBackground(ImageProcessor ip, double radius, boolean createBackground, boolean lightBackground, boolean useParaboloid, boolean doPresmooth, boolean correctCorners) 
			bs.rollingBallBackground(ip, radius, False, light, False, True, False)
			peak=ip.getPixel(x,y)
			tol = peak*seuil
			w = Wand(ip)
			w.autoOutline(x, y, tol, Wand.EIGHT_CONNECTED)
			ip.reset()
			#print "method=", method, tol, radius, peak
			
		else : 
			peak=ip.getPixel(x,y)
			tol = peak*seuil
			w = Wand(ip)
			w.autoOutline(x, y, tol, Wand.EIGHT_CONNECTED)
			#print "method=", method, tol

		peak=ip.getPixel(x,y)
		temproi=PolygonRoi(w.xpoints, w.ypoints, w.npoints, PolygonRoi.POLYGON)
		self.__image.setRoi(temproi)
		#self.__image.show()
		#time.sleep(1)
		#peakip=self.__image.getProcessor()
		#stats=peakip.getStatistics()
		temprt = ResultsTable()
		analyser = Analyzer(self.__image, Analyzer.AREA+Analyzer.INTEGRATED_DENSITY+Analyzer.FERET, temprt)
		analyser.measure()
		#temprt.show("temprt")
		rtValues=temprt.getRowAsString(0).split("\t")
		area=float(rtValues[1])
		intDen=float(rtValues[4])
		feret=float(rtValues[2])
		mean=intDen/area
		#time.sleep(2)
		temprt.reset()
		self.__image.killRoi()
		return [peak, area, mean, intDen, feret]
					
		
	
	def __MidProfil(self):
		if not self.__boolML :  self.__midline()
		ip=self.__image.getProcessor()
		line=Line(self.__midLine[0][0],self.__midLine[0][1],self.__midLine[-1][0],self.__midLine[-1][1])
		line.setWidth(self.__lw)

		self.__MprofArray=[]
		self.__MprofArray[:]=[]
		for i in range(0,len(self.__midLine)-1):
			templine=Line(self.__midLine[i][0],self.__midLine[i][1],self.__midLine[i+1][0],self.__midLine[i+1][1])
			templine.setWidth(self.__lw)
			self.__image.setRoi(templine)
			#time.sleep(0.5)
			temprof= ProfilePlot(self.__image)
			temparray=temprof.getProfile()
			self.__MprofArray+=temparray
		templine.setWidth(0)
		#if self.__showMidpro: self.__fprof.createWindow()	 
		return
		
	def getFeretSegments(self, n):
		self.__boolFS=True
		if(not self.__boolFL):
			self.__FeretAxis()
		radius=self.getMinF()
		lsegment=self.__line.getLength()/((n-1)*2)
		xo=self.__x1
		yo=self.__y1
		xf=self.__x2
		yf=self.__y2
		angle1=self.getAngF()*(math.pi/180)
		angle2=self.getAngF()*(math.pi/180)+(math.pi/2)
		avancex=(lsegment*2)*math.cos(angle1)
		avancey=(lsegment*2)*math.sin(angle1)
		delta90x=(radius)*math.cos(angle2)
		delta90y=(radius)*math.sin(angle2)
		self.__line.setWidth(int(lsegment*2))
		#self.__image.setRoi(self.__line)
		tempcontour=self.__contour.clone()
		shapeContour=ShapeRoi(tempcontour)
		segsRoi=[]
		for i in range(n):
			tempLine=Line(xo-delta90x, yo+delta90y, xo+delta90x, yo-delta90y)
			tempLine.setWidth(int(lsegment*2))
			poly=tempLine.getPolygon()
			roipol=PolygonRoi(poly, Roi.POLYGON)
			shapePoly= ShapeRoi(roipol)
			interShape=shapePoly.and(shapeContour)
			segsRoi.append(interShape.shapeToRoi())
			xo=xo+avancex
			yo=yo-avancey

		
		#self.__image.setRoi(self.__contour, True)
		#time.sleep(0)
		self.__line.setWidth(0)
		#self.__image.setRoi(tempcontour)
		
		#self.__image.updateAndDraw() 
		
		return segsRoi # return Roi array

	def getMidSegments(self, n=10, r=5, tool=0):
		self.__boolMS=True
		if(not self.__boolML):
			self.__midline()
		lsegment=int(len(self.__midLine)/n)
		if lsegment<2:lsegment=2
		ls2=int(len(self.__midLine)/(2*n))
		if ls2<1: ls2=1
		ip=self.__image.getProcessor()
		#print(len(self.__midLine), lsegment, ls2)
		xo=self.__MidBouts[0][0]
		yo=self.__MidBouts[0][1]
		xf=self.__MidBouts[1][0]
		yf=self.__MidBouts[1][1]
		line1=Line(xo,yo,xf,yf)
		line1.setWidth(0)
		angles=[line1.getAngle(self.__midLine[i][0], self.__midLine[i][1], self.__midLine[i+lsegment][0], self.__midLine[i+lsegment][1]) for i in range(0,len(self.__midLine)-lsegment,lsegment)]
		points=[self.__midLine[i] for i in range(0,len(self.__midLine),lsegment)]
		lastangle=line1.getAngle(self.__midLine[-ls2][0],self.__midLine[-ls2][1],self.__midLine[-1][0],self.__midLine[-1][1])
		angles.append(lastangle)
		tempcontour=self.__contour.clone()
		shapeContour=ShapeRoi(tempcontour)
		angles=[angle*(math.pi/180)+(math.pi/2) for angle in angles]
		line1.setWidth((ls2+1)*2)
		segsRoi=[]
		linesRois=[]
		cRois=[]
		for i in range(len(angles)):
			x=points[i][0]
			y=points[i][1]
			cRois.append(PointRoi(x,y))
			if tool==0: # ligne perpendiculaire d'epaiseur  (ls2+1)*2
				line1.setWidth((ls2+1)*2)
				x1=x+r*math.cos(angles[i])
				y1=y-r*math.sin(angles[i])
				x2=x-r*math.cos(angles[i])
				y2=y+r*math.sin(angles[i])
				#print(x, y, x1, y1, x2, y2)
				tempLine=Line(x1,y1,x2,y2)
				linesRois.append(tempLine)
				tempLine.setWidth((ls2+1)*2)
				#self.__image.setRoi(tempLine, True)
				#time.sleep(0.3)
				poly=tempLine.getPolygon()
				roipol=PolygonRoi(poly, Roi.POLYGON)
				shapePoly= ShapeRoi(roipol)
			elif tool==1:
				#r1=r*0.7
				x1=x+r
				y1=y-r
				x2=x-r
				y2=y+r
				ellipse=EllipseRoi(x1, y1, x2, y2, 1)
				linesRois.append(ellipse)
				#print(x, y, x1, y1, x2, y2)
				#self.__image.setRoi(ellipse, True)
				shapePoly= ShapeRoi(ellipse)
				#time.sleep(0.3)
			else:
				x1=x
				y1=y
				line1.setWidth(r)
				if (i+1)<len(points):
					x2=points[i+1][0]
					y2=points[i+1][1]
				else:
					#x1=x+lsegment*math.cos(angles[i]-(math.pi/2))
					#y1=y-lsegment*math.sin(angles[i]-(math.pi/2))
					x2=x+lsegment*math.cos(angles[i]-(math.pi/2))
					y2=y-lsegment*math.sin(angles[i]-(math.pi/2))
					#x2=xf
					#y2=yf
				
				tempLine=Line(x1,y1,x2,y2)
				linesRois.append(tempLine)
				tempLine.setWidth(r)
				#self.__image.setRoi(tempLine, True)
				#time.sleep(0.5)
				poly=tempLine.getPolygon()
				roipol=PolygonRoi(poly, Roi.POLYGON)
				shapePoly= ShapeRoi(roipol)
			
			interShape=shapePoly.and(shapeContour)
			interRoi=interShape.shapeToRoi()
			segsRoi.append(interShape.shapeToRoi())
		line1.setWidth(0)
		return (segsRoi, linesRois, cRois)

	def selectInitRoi(self):
		self.__image.killRoi()
		self.__image.setRoi(self.__contour)
		time.sleep(0)

	@staticmethod
	def distMorph(coord,distmethod="Euclidean distance"):
		if distmethod == "Euclidean distance" :
			s=[val[0]*(val[2]-val[1])*(val[2]-val[1]) for val in coord]
			#print s
			#print sum(s)
			return math.sqrt(sum(s))
		if distmethod == "Logarithm distance" :
			s=[val[0]*abs(math.log(val[2]/val[1])) for val in coord]
			return sum(s)
			
	@staticmethod
	def log2(n) : return math.log(n)/math.log(2)
	
	def Out(self): print("out")

	

#------ end methodes---------------
#------ constructeur -------------

	def __init__(self, imp, roi):
		self.__lw=0
		self.__showFpro=False
		self.__Feret=[] 
		self.__image=imp
		self.__cal=imp.getCalibration()
		self.__contour=roi.clone()
		self.__boolmeasures=False
		self.__boolFP=False
		self.__boolFL=False
		self.__boolML=False
		self.__boolMP=False
		self.__boolFS=False
		self.__boolMS=False
		self.__boolFoci=False
		self.__midParams=[10, 1.3]
		self.__listMax=[]
		self.__noise=150
		self.__seuilPeaks=0.75
		self.__peaksMethod="mean"
		self.__light=False
		self.__distot=0.00
		self.__flexangle=0.00
		#print "dropbox MorphoBactProject"
	
#---------- end constructor---------
#---------- getteurs----------------
	
	def getMaxF(self):
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("Feret", 0)
	def getMinF(self):
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("MinFeret", 0)
	def getXF(self):
		if(not self.__boolmeasures): self.__Measures() 
		return self.__rt.getValue("FeretX", 0)
	def getYF(self): 
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("FeretY", 0)
	def getAngF(self):
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("FeretAngle", 0)
	def getArea(self): 
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("Area", 0)
	def getMean(self):
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("Mean", 0)
	def getKurt(self):
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("Kurt", 0)
	def getSkew(self):
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("Skew", 0)
	def getIntDen(self):
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("IntDen", 0)
	def getStdDev(self):
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("StdDev", 0)
	def getAngle(self): 
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("Angle", 0)
	def getMajor(self): 
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("Major", 0)
	def getMinor(self): 
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("Minor", 0)
	def getSolidity(self): 
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("Solidity", 0)
	def getAR(self): 
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("AR", 0)
	def getRound(self): 
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("Round", 0)
	def getCirc(self): 
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("Circ.", 0)
	def getXM(self): 
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("XM",0)
	def getYM(self): 
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("YM",0)
	def getXC(self): 
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("X",0)
	def getYC(self): 
		if(not self.__boolmeasures): self.__Measures()
		return self.__rt.getValue("Y",0)

	def getNfoci(self):
		if(not self.__boolFoci):self.__NbFoci()
		return len(self.__listMax)

	def getListFoci(self):
		if(not self.__boolFoci):self.__NbFoci()
		xy=[]
		for val in self.__listMax:
			xy.append((val[0], val[1]))
		return xy

	def getListPeaksFoci(self):
		if(not self.__boolFoci):self.__NbFoci()
		peaks=[]
		for val in self.__listMax:
			peaks.append(val[2])
		return peaks

	def getListAreaFoci(self):
		if(not self.__boolFoci):self.__NbFoci()
		areas=[]
		for val in self.__listMax:
			areas.append(val[3])
		return areas

	def getListMeanFoci(self):
		if(not self.__boolFoci):self.__NbFoci()
		means=[]
		for val in self.__listMax:
			means.append(val[4])
		return means

	def getListIntDenFoci(self):
		if(not self.__boolFoci):self.__NbFoci()
		ints=[]
		for val in self.__listMax:
			ints.append(val[5])
		return ints

	def getListFeretFoci(self):
		if(not self.__boolFoci):self.__NbFoci()
		ferets=[]
		for val in self.__listMax:
			ferets.append(val[6])
		return ferets

	def getListDistsFoci(self):
		if(not self.__boolFoci):self.__NbFoci()
		dists=[]
		for val in self.__listMax:
			dists.append(val[7])
		return dists

	def getFercoord(self):
		"""
			FerCoord: tuple contenant x1, y1, x2, y2 du MaxFeret
		"""
		if (not self.__boolFL): self.__FeretAxis()
		return (self.__x1,self.__y1,self.__x2,self.__y2)
	def getFprofil(self):
		"""
			Fprofil: list contenant les valeurs du profil le long de MaxFeret
		"""
		if (not self.__boolFL): self.__FeretAxis()
		self.__FeretProfile()
		return self.__fprofArray
	def getFerAxis(self):
		"""
			FerAxis: Line ROI
		"""
		if(not self.__boolFL): self.__FeretAxis()
		return self.__line
		
	def getMidAxis(self):
		"""
			MidAxis: Polyline ROI de l'axe median par skeletonize
		"""
		if(not self.__boolML): return self.__midline()

	def getMidSegs(self, n, r, tool):
		"""
			Rois des segments 0 = rois , 1 = points, 2 = lines ou ellipses
		"""
		if(not self.__boolMS): return self.getMidSegments(n, r, tool)
		
	def getMidProfil(self):
		"""
			MidProfil: list contenant les valeurs du profil le long de MidAxis
		"""
		self.__MidProfil()
		return self.__MprofArray

	def getMidPoints(self) :
		"""
			MidPoints : list of two extreme points of mid Axis
		"""
		if(not self.__boolML): self.__midline()
		return self.__MidBouts

	def getCenters(self) :
		if(not self.__boolML): self.__midline()
		return self.__midCenters

	def getFlexAngle(self) :
		return self.__flexAngle()


#------ setteurs --------

	def setImage(self, imp):
		self.__image=imp

	def setImageMeasures(self, imp):
		self.__image=imp
		self.__Measures()
		
	def setImageFprofil(self, imp):
		self.__image=imp
		self.__FeretProfile()

	def setImageMidprofil(self, imp):
		self.__image=imp
		self.__MidProfil()

	def setLineWidth(self, lw):
		self.__lw=lw

	def setshowFpro(self, fpshow):
		self.__showFpro=fpshow

	def setMidParams(self, lseg, coeff):
		self.__midParams[:]=[]
		self.__midParams.append(lseg)
		self.__midParams.append(coeff)

	def setNoise(self, noise):
		self.__noise=noise

	def setSeuilPeaks(self, seuil):
		self.__seuilPeaks=seuil

	def setpeaksMethod(self, method):
		self.__peaksMethod=method

	def setlight(self, light):
		self.__light=light

		
#------- properties -----------------------
	
	MaxFeret=property(getMaxF, setImageMeasures, doc="caliper max Feret=")
	MinFeret=property(getMinF, setImageMeasures, doc="caliper min Feret=")
	AngleFeret=property(getAngF, setImageMeasures, doc="angle Feret=")
	XFeret=property(getXF, setImageMeasures, doc="X Feret=")
	YFeret=property(getYF, setImageMeasures, doc="Y Feret=")
	Area=property(getArea, setImageMeasures, doc="Area=")
	Mean=property(getMean, setImageMeasures, doc="Mean=")
	Kurt=property(getKurt, setImageMeasures, doc="Kurtosis=")
	Skew=property(getSkew, setImageMeasures, doc="Skewness=")
	IntDen=property(getIntDen, setImageMeasures, doc="Integrated Intensity=")
	StdDev=property(getStdDev, setImageMeasures, doc="Standard Deviation=")
	Angle=property(getAngle, setImageMeasures, doc="Angle=")
	Major=property(getMajor, setImageMeasures, doc="Major ellipse axis=")
	Minor=property(getMinor, setImageMeasures, doc="Minor ellipse axis=")
	Solidity=property(getSolidity, setImageMeasures, doc="Solidity area/convexHull=")
	AR=property(getAR, setImageMeasures, doc="Major axis/Minor axis=")
	Round=property(getRound, setImageMeasures, doc="Area/(pi*Major*Major)=1/AR=")
	Circ=property(getCirc, setImageMeasures, doc="(4*pi*Area)/(perimeter*perimeter)=")
	XM=property(getXM, setImageMeasures, doc="X center of Mass=")
	YM=property(getYM, setImageMeasures, doc="Y center of Mass=")
	XC=property(getXC, setImageMeasures, doc="X of centroid=")
	YC=property(getYC, setImageMeasures, doc="Y of centroid=")
	
	NFoci=property(getNfoci, setImageMeasures, doc="nb foci in the roi=")
	ListFoci=property(getListFoci, setImageMeasures, doc="list of foci coordinates=")
	ListPeaksFoci=property(getListPeaksFoci, setImageMeasures, doc="list of foci peaks=")
	ListAreaFoci=property(getListAreaFoci, setImageMeasures, doc="list of foci areas=")
	ListMeanFoci=property(getListMeanFoci, setImageMeasures, doc="list of foci means=")
	ListIntDenFoci=property(getListIntDenFoci, setImageMeasures, doc="list of foci IntDen=")
	ListFeretFoci=property(getListFeretFoci, setImageMeasures, doc="list of foci Ferets=")
	ListDistsFoci=property(getListDistsFoci, setImageMeasures, doc="list of foci distances=")
	
	FerCoord=property(getFercoord, doc="x1, y1, x2, y2 of Feret diameter =")
	Fprofil=property(getFprofil, setImageFprofil, doc="Profil along Feret diameter") 	# return array values
	FerAxis=property(getFerAxis, doc="ROI along Feret diameter")				# return Roi
	
	MidAxis=property(getMidAxis, doc="ROI along the median axis")				# return Roi
	MidProfil=property(getMidProfil, setImageMidprofil, doc="profile values of mid axis")	# return array values
	MidPoints=property(getMidPoints, doc= "extreme points of mid line")

	Centers=property(getCenters, doc= "list of positions (tuples) of 1/2 of the midaxis, 1/4, 1/8 ...") # return a list of tuples
	FlexAngle=property(getFlexAngle, doc="angle of the center of midline to ends")	
 def getEuclidean(self):
     """return the length of the straight line joining start and end points of the membrane"""
     poly = self.roi.getInterpolatedPolygon(1, True)
     line = Line(poly.xpoints[0], poly.ypoints[0], poly.xpoints[-1],
                 poly.ypoints[-1])
     return line.getLength()
Beispiel #10
0
# using a default generic RealType converter via t.setReal(t.getRealDouble())
compute(op).into(blurred, None, FloatType(), None)

# Show the blurred image with the same LUT as the original
imp2 = IL.wrap(blurred, "integral image radius 5 blur")
imp2.getProcessor().setLut(imp.getProcessor().getLut())
imp2.show()

# Compare with Gaussian blur
from ij import ImagePlus
from ij.plugin.filter import GaussianBlur
from ij.gui import Line, ProfilePlot

# Gaussian of the original image
imp_gauss = ImagePlus(imp.getTitle() + " Gauss",
                      imp.getProcessor().duplicate())
GaussianBlur().blurGaussian(imp_gauss.getProcessor(), radius)
imp_gauss.show()

# Plot values from a diagonal from bottom left to top right
line = Line(imp.getWidth() - 1, 0, 0, imp.getHeight() - 1)
imp_gauss.setRoi(line)
pp1 = ProfilePlot(imp_gauss)
plot = pp1.getPlot()
imp2.setRoi(line)
pp2 = ProfilePlot(imp2)
profile2 = pp2.getProfile()  # double[]
plot.setColor("red")
plot.add("line", range(len(profile2)), profile2)
plot.show()
Beispiel #11
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
Beispiel #12
0
def makeArrow(x1, y1, x2, y2):
    IJ.setTool("arrow")
    imp = IJ.getImage()
    imp.setRoi(Line(x1, y1, x2, y2))
Beispiel #13
0
def do_angular_projection(imp,
                          max_r_pix=60,
                          min_r_pix=10,
                          generate_roi_stack=True):
    """perform ray-based projection of vessel wall, c.f. ICY TubeSkinner (Lancino 2018)"""
    Prefs.blackBackground = True
    print("do angular projection input imp = " + str(imp))
    split_chs = ChannelSplitter().split(imp)
    mch_imp = split_chs[0]
    IJ.setAutoThreshold(mch_imp, "IsoData dark stack")
    egfp_imp = split_chs[1]
    proj_imp = Duplicator().run(egfp_imp)
    cl_imp = split_chs[2]
    if generate_roi_stack:
        egfp_imp_disp = Duplicator().run(egfp_imp)
        roi_stack = IJ.createImage("rois", egfp_imp.getWidth(),
                                   egfp_imp.getHeight(), egfp_imp.getNSlices(),
                                   16)

    centres = []
    projected_im_pix = []
    ring_rois = []
    for zidx in range(cl_imp.getNSlices()):
        if ((zidx + 1) % 100) == 0:
            print("Progress = " +
                  str(round(100 * (float(zidx + 1) / cl_imp.getNSlices()))))
        projected_im_row = []
        proj_imp.setZ(zidx + 1)
        mch_imp.setZ(zidx + 1)
        bp = mch_imp.createThresholdMask()
        bp.dilate()
        bp.erode()
        bp.erode()
        bp.erode()
        mask_imp = ImagePlus("mask", bp)
        IJ.run(mask_imp, "Create Selection", "")
        roi = mask_imp.getRoi()
        proj_imp.setRoi(roi)
        IJ.run(proj_imp, "Set...", "value=0 slice")
        IJ.run(proj_imp, "Make Inverse", "")
        roi = proj_imp.getRoi()
        centre = (roi.getStatistics().xCentroid, roi.getStatistics().yCentroid)
        centres.append(centre)
        ring_roi_xs = []
        ring_roi_ys = []
        for theta in range(360):
            pt1 = (centre[0] + min_r_pix * math.cos(math.radians(theta)),
                   centre[1] + min_r_pix * math.sin(math.radians(theta)))
            pt2 = (centre[0] + max_r_pix * math.cos(math.radians(theta)),
                   centre[1] + max_r_pix * math.sin(math.radians(theta)))
            roi = Line(pt1[0], pt1[1], pt2[0], pt2[1])
            proj_imp.setRoi(roi)
            profile = roi.getPixels()
            projected_im_row.append(max(profile))
            try:
                ring_roi_xs.append(roi.getContainedPoints()[profile.index(
                    max(profile))].x)
            except IndexError:
                ring_roi_xs.append(pt2[0])
            try:
                ring_roi_ys.append(roi.getContainedPoints()[profile.index(
                    max(profile))].y)
            except IndexError:
                ring_roi_ys.append(pt2[1])
            proj_imp.killRoi()
        ring_roi = PolygonRoi(ring_roi_xs, ring_roi_ys, Roi.FREELINE)
        ring_rois.append(ring_roi)
        if generate_roi_stack:
            roi_stack.setZ(zidx + 1)
            roi_stack.setRoi(ring_roi)
            IJ.run(roi_stack, "Line to Area", "")
            IJ.run(
                roi_stack, "Set...",
                "value=" + str(roi_stack.getProcessor().maxValue()) + " slice")
        #egfp_imp.setRoi(ring_roi);
        projected_im_pix.append(projected_im_row)


#	for ch in split_chs:
#		ch.close();

    out_imp = ImagePlus(
        "projected", FloatProcessor([list(x) for x in zip(*projected_im_pix)]))

    if generate_roi_stack:
        roi_stack.show()
        egfp_imp_disp.show()
        # merge?
    else:
        roi_stack = None
    return out_imp, roi_stack, ring_rois, centres
for bp in brightestpixellist:
	x = bp%imp.width
	y = bp/imp.width
	#print "max. brightness coordinates:", x, y

# note that the following chooses for x, y the last element in the brightestpixelist which is OK if there is only one element
# TODO: would be nicer to loop over this list or specify which element to pick

length = 400/2
angular_accuracy = 5 # degrees

for alpha in range(0, 180, angular_accuracy):
	myimp = ImagePlus("Profile_"+str(alpha), ip)
	vecx, vecy = length * cos(alpha * pi/180), length * sin(alpha * pi/180)
	roi = Line(x-vecx, y-vecy, x+vecx, y+vecy)
	myimp.setRoi(roi)
	#ip.draw(roi) # enabling this creates artifacts - careful!

	# create ProfilePlot
	profplot = ProfilePlot(myimp)
	#profplot.createWindow()  # enabling this creates a nice animation
	#print alpha, sum(profplot.getProfile())/len(profplot.getProfile()) # test: average of profile values as proxy for brightness

	# get the data
	profarray = profplot.getProfile()

	# smooth the data by calculating moving average
	win = 12 # window size for moving average, must be even
	movavg = moving_average(profarray, win)
	medi = median(movavg)
Beispiel #15
0
	def getMidSegments(self, n=10, r=5, tool=0):
		self.__boolMS=True
		if(not self.__boolML):
			self.__midline()
		lsegment=int(len(self.__midLine)/n)
		if lsegment<2:lsegment=2
		ls2=int(len(self.__midLine)/(2*n))
		if ls2<1: ls2=1
		ip=self.__image.getProcessor()
		#print(len(self.__midLine), lsegment, ls2)
		xo=self.__MidBouts[0][0]
		yo=self.__MidBouts[0][1]
		xf=self.__MidBouts[1][0]
		yf=self.__MidBouts[1][1]
		line1=Line(xo,yo,xf,yf)
		line1.setWidth(0)
		angles=[line1.getAngle(self.__midLine[i][0], self.__midLine[i][1], self.__midLine[i+lsegment][0], self.__midLine[i+lsegment][1]) for i in range(0,len(self.__midLine)-lsegment,lsegment)]
		points=[self.__midLine[i] for i in range(0,len(self.__midLine),lsegment)]
		lastangle=line1.getAngle(self.__midLine[-ls2][0],self.__midLine[-ls2][1],self.__midLine[-1][0],self.__midLine[-1][1])
		angles.append(lastangle)
		tempcontour=self.__contour.clone()
		shapeContour=ShapeRoi(tempcontour)
		angles=[angle*(math.pi/180)+(math.pi/2) for angle in angles]
		line1.setWidth((ls2+1)*2)
		segsRoi=[]
		linesRois=[]
		cRois=[]
		for i in range(len(angles)):
			x=points[i][0]
			y=points[i][1]
			cRois.append(PointRoi(x,y))
			if tool==0: # ligne perpendiculaire d'epaiseur  (ls2+1)*2
				line1.setWidth((ls2+1)*2)
				x1=x+r*math.cos(angles[i])
				y1=y-r*math.sin(angles[i])
				x2=x-r*math.cos(angles[i])
				y2=y+r*math.sin(angles[i])
				#print(x, y, x1, y1, x2, y2)
				tempLine=Line(x1,y1,x2,y2)
				linesRois.append(tempLine)
				tempLine.setWidth((ls2+1)*2)
				#self.__image.setRoi(tempLine, True)
				#time.sleep(0.3)
				poly=tempLine.getPolygon()
				roipol=PolygonRoi(poly, Roi.POLYGON)
				shapePoly= ShapeRoi(roipol)
			elif tool==1:
				#r1=r*0.7
				x1=x+r
				y1=y-r
				x2=x-r
				y2=y+r
				ellipse=EllipseRoi(x1, y1, x2, y2, 1)
				linesRois.append(ellipse)
				#print(x, y, x1, y1, x2, y2)
				#self.__image.setRoi(ellipse, True)
				shapePoly= ShapeRoi(ellipse)
				#time.sleep(0.3)
			else:
				x1=x
				y1=y
				line1.setWidth(r)
				if (i+1)<len(points):
					x2=points[i+1][0]
					y2=points[i+1][1]
				else:
					#x1=x+lsegment*math.cos(angles[i]-(math.pi/2))
					#y1=y-lsegment*math.sin(angles[i]-(math.pi/2))
					x2=x+lsegment*math.cos(angles[i]-(math.pi/2))
					y2=y-lsegment*math.sin(angles[i]-(math.pi/2))
					#x2=xf
					#y2=yf
				
				tempLine=Line(x1,y1,x2,y2)
				linesRois.append(tempLine)
				tempLine.setWidth(r)
				#self.__image.setRoi(tempLine, True)
				#time.sleep(0.5)
				poly=tempLine.getPolygon()
				roipol=PolygonRoi(poly, Roi.POLYGON)
				shapePoly= ShapeRoi(roipol)
			
			interShape=shapePoly.and(shapeContour)
			interRoi=interShape.shapeToRoi()
			segsRoi.append(interShape.shapeToRoi())
		line1.setWidth(0)
		return (segsRoi, linesRois, cRois)
Beispiel #16
0
from ij import IJ, WindowManager
from ij.gui import Line

IJ.run("Close All")
imp = IJ.openImage("/Users/jrminter/Downloads/three_phase.jpeg")
IJ.run(imp, "RGB to CIELAB", "")
IJ.run("Stack to Images", "")
imp_L = WindowManager.getImage("L")
imp_a = WindowManager.getImage("a")
imp_b = WindowManager.getImage("b")
the_line = Line(0,178,690,178)
the_line.setWidth(20) 
imp_L.setRoi(the_line)
imp_L.show()
IJ.run(imp_L, "Plot Profile", "")
imp_a.setRoi(Line(0,231,690,220))
IJ.run(imp_a, "Plot Profile", "")
imp_a.show()

Beispiel #17
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 #18
0
	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
Beispiel #19
0
	def __addroi(self, event) :
		if ( not self.__init) : 
			IJ.showMessage("", "please start a new stack")
			return
		if ( not self.__initDIA) :
			IJ.showMessage("", "please select an image for DIA")
			return

		if ( not self.__initFLUO) :
			IJ.showMessage("", "please select an image for FLUO")
			return

		twres = TextWindow("measures-"+self.__name, "label\tname\tsol\tarea\tcirc\tAR\tFeret\taxis\traf\tdMajor\tdFeret\tdArea", "", 300, 450)
		tab="\t"
		
		self.__widthl = self.__display2.getText()
		IJ.selectWindow(self.__impF.getTitle())

		self.__rm = RoiManager.getInstance()
		if (self.__rm==None): self.__rm = RoiManager()

		if self.__impF.getImageStackSize() > 1 :
			roisarray =[(roi, self.__rm.getSliceNumber(roi.getName())) for roi in self.__rm.getRoisAsArray()]
		else : 
			roisarray =[(roi, 1) for roi in self.__rm.getRoisAsArray()]
			
		self.__rm.runCommand("reset")
		#self.__rm.runCommand("Delete")
		IJ.selectWindow(self.__impF.getTitle())

		self.__maxraf=float(self.__display19.text)
		self.__minraf=float(self.__display20.text)

		count=1

		for roielement in roisarray :
			roi = roielement[0]
			pos = roielement[1]
			lab = self.__impF.getImageStack().getShortSliceLabel(pos)

			if lab==None : lab=str(pos)
			
			if self.__conEllipses :
				IJ.selectWindow(self.__impF.getTitle())
				self.__impF.setSlice(pos)
				self.__impF.setRoi(roi)
				self.__rm.runCommand("Add")
				IJ.run(self.__impF,  "Fit Ellipse", "")
				ellipse=self.__impF.getRoi()
				params = ellipse.getParams()
				ferets = ellipse.getFeretValues()
				imp2 = Duplicator().run(self.__impF,pos,pos)
				IJ.run(imp2, "Rotate... ", "angle="+str(ferets[1])+" grid=0 interpolation=Bilinear enlarge slice")
				temproi=Roi((imp2.getWidth()-ferets[0])/2.0,(imp2.getHeight()-ferets[2])/2.0,ferets[0],ferets[2])
				imp2.setRoi(temproi)
				imp3 = Duplicator().run(imp2,1,1)
				ip3=imp3.getProcessor()

				if int(self.__display5.text) < ip3.getWidth() < int(self.__display6.text) : 
					self.__iplist.append(ip3)
					self.__display.text = self.__name + " cell " + str(len(self.__iplist))
					fer=Line(params[0],params[1],params[2],params[3])
					self.__cellsrois.append((fer, pos))
					self.__labels.append(self.__isF.getShortSliceLabel(pos))

				m=Morph(self.__impF, roi)

				twres.append(lab+tab+str(roi.getName())+tab+str(m.Solidity)+tab+str(m.Area)+tab+str(m.Circ)+tab+str(m.AR)+tab+str(m.MaxFeret)+tab+str(fer.getLength())+tab+str(1)+tab+str(0)+tab+str(0)+tab+str(0))
				self.__dictCells[count]=(str(roi.getName()), lab, roi)
				count=count+1
				continue
			
			if roi.getType() in [6,7] : 
				self.__impF.setSlice(pos)
				self.__impF.setRoi(roi)
				self.__rm.runCommand("Add")

			elif roi.getType() in [2,4] :
				self.__impF.setSlice(pos)
				self.__impF.setRoi(roi)
				m=Morph(self.__impF, roi)
				m.setMidParams(10, 2)
				midroi=m.MidAxis
				if midroi == None : continue

				raf = m.MaxFeret/midroi.getLength()
				
				if (self.__maxraf < raf) or (raf < self.__minraf) : continue

				maxsol = float(self.__display7.text)
				minsol = float(self.__display8.text)
				maxarea = float(self.__display9.text)
				minarea = float(self.__display10.text)
				maxcirc = float(self.__display11.text)
				mincirc = float(self.__display12.text)
				maxar = float(self.__display13.text)
				minar = float(self.__display14.text)
				maxfer = float(self.__display15.text)
				minfer = float(self.__display16.text)
				maxmean = float(self.__display17.text)
				minmean = float(self.__display18.text)
				maxmferet = float(self.__display21.text)
				minmferet = float(self.__display22.text)

				testsol = (minsol<= m.Solidity <= maxsol)
				testarea = (minarea<= m.Area <= maxarea)
				testcirc = (mincirc<= m.Circ <= maxcirc)
				testar = (minar<= m.AR <= maxar)
				testfer = (minfer<= m.MaxFeret <= maxfer)
				testmean = (minmean <= m.Mean <= maxmean)
				testmferet = (minmferet <= m.MinFeret <= maxmferet)
				
				#print minmferet , m.MinFeret , maxmferet

				test = (testsol+testarea+testcirc+testar+testfer+testmean+testmferet)/7	

				if test : 				
					fmaj, ffmx, fa =[],[],[]
					for r in m.getMidSegments(10, 40, 0)[0] :
						if r == None : continue
						m2=Morph(self.__impF, r)
						fmaj.append(m2.Major)
						ffmx.append(m2.MaxFeret)
						fa.append(m2.Area)

					diffmajor, diffferet, diffarea = 0,0,0
					
					if len(fa) > 4 :
						medfmaj = self.listmean(fmaj[1:-1])
						medffmx = self.listmean(ffmx[1:-1])
						medfa   = self.listmean(fa[1:-1])

						diffmajor = (max(fmaj[1:-1])-medfmaj)/medfmaj
						diffferet = (max(ffmx[1:-1])-medffmx)/medffmx
						diffarea = (max(fa[1:-1])-medfa)/medfa

					twres.append(lab+tab+str(roi.getName())+tab+str(m.Solidity)+tab+str(m.Area)+tab+str(m.Circ)+tab+str(m.AR)+tab+str(m.MaxFeret)+tab+str(midroi.getLength())+tab+str(m.MaxFeret/midroi.getLength())+tab+str(diffmajor)+tab+str(diffferet)+tab+str(diffarea))
					#print lab+tab+str(roi.getName())+tab+str(m.Solidity)+tab+str(m.Area)+tab+str(m.Circ)+tab+str(m.AR)+tab+str(m.MaxFeret)+tab+str(midroi.getLength())+tab+str(m.MaxFeret/midroi.getLength())+tab+str(diffmajor)+tab+str(diffferet)+tab+str(diffarea)

					self.__impF.setRoi(roi)
					self.__rm.runCommand("Add")
					self.__impF.killRoi()
					self.__impF.setRoi(midroi)
					
					#self.__dictCells[str(roi.getName())]=(str(roi.getName()), lab, roi)
					self.__dictCells[count]=(str(roi.getName()), lab, roi)
					count=count+1
					
				else : 
					#print "test falls"
					continue

			else : 
				print "out loop"
				continue
			
			straightener = Straightener()
			new_ip = straightener.straighten(self.__impF, midroi, int(self.__widthl))
			if int(self.__display5.text) < new_ip.getWidth() < int(self.__display6.text) : 
				self.__iplist.append(new_ip.convertToShort(False))
				self.__display.text = self.__name + " cell " + str(len(self.__iplist))
				#print "add", roi.getName(), roi.getType()
				self.__cellsrois.append((midroi, pos))
				self.__labels.append(self.__isF.getShortSliceLabel(pos))


		#roisarray=self.__rm.getRoisAsArray()		
		#self.__rm.runCommand("reset")
		#self.__rm.runCommand("Delete")
		

		self.__impD.killRoi()
		self.__impF.killRoi()
		IJ.selectWindow(self.__impD.getTitle()) 
Beispiel #20
0
def batch_open_images(pathImage, file_typeImage, name_filterImage=None):

    if isinstance(pathImage, File):
        pathImage = pathImage.getAbsolutePath()

    def check_filter(string):
        '''This function is used to check for a given filter.
        It is possible to use a single string or a list/tuple of strings as filter.
        This function can access the variables of the surrounding function.
        :param string: The filename to perform the filtering on.
        '''
        if name_filterImage:
            # The first branch is used if name_filter is a list or a tuple.
            if isinstance(name_filterImage, (list, tuple)):
                for name_filter_ in name_filterImage:
                    if name_filter_ in string:
                        # Exit the function with True.

                        return True
                    else:
                        # Next iteration of the for loop.
                        continue
            # The second branch is used if name_filter is a string.
            elif isinstance(name_filterImage, string):
                if name_filterImage in string:
                    return True
                else:
                    return False
            return False
        else:
            # Accept all files if name_filter is None.
            return True

    def check_type(string):
        '''This function is used to check the file type.
        It is possible to use a single string or a list/tuple of strings as filter.
        This function can access the variables of the surrounding function.
        :param string: The filename to perform the check on.
        '''
        if file_typeImage:
            # The first branch is used if file_type is a list or a tuple.
            if isinstance(file_typeImage, (list, tuple)):
                for file_type_ in file_typeImage:
                    if string.endswith(file_type_):
                        # Exit the function with True.
                        return True
                    else:
                        # Next iteration of the for loop.
                        continue
            # The second branch is used if file_type is a string.
            elif isinstance(file_typeImage, string):
                if string.endswith(file_typeImage):
                    return True
                else:
                    return False
            return False
        # Accept all files if file_type is None.
        else:
            return True

    # We collect all files to open in a list.
    path_to_Image = []
    # Replacing some abbreviations (e.g. $HOME on Linux).
    path = os.path.expanduser(pathImage)
    path = os.path.expandvars(pathImage)
    # If we don't want a recursive search, we can use os.listdir().

    for directory, dir_names, file_names in os.walk(pathImage):
        # We are only interested in files.
        for file_name in file_names:
            # The list contains only the file names.
            # The full path needs to be reconstructed.
            full_path = os.path.join(directory, file_name)
            # Both checks are performed to filter the files.
            if check_type(file_name):
                if check_filter(file_name) is False:
                    # Add the file to the list of images to open.
                    path_to_Image.append([
                        full_path,
                        os.path.basename(os.path.splitext(full_path)[0])
                    ])
    Images = []

    for img_path, file_name in path_to_Image:

        imp = IJ.openImage(img_path)
        maskimage = ops.run("create.img", imp)
        cursor = maskimage.localizingCursor()
        imp.show()
        IJ.run("Select None")
        overlay = imp.getOverlay()
        if overlay == None:

            overlay = Overlay()
            imp.setOverlay(overlay)
        else:

            overlay.clear()

        imp.updateAndDraw()
        impY = imp.getHeight()
        impX = imp.getWidth()
        print(impY, impX)
        rm = RoiManager.getInstance()
        if not rm:
            rm = RoiManager()

        rm.runCommand("reset")
        WaitForUserDialog("Select the landmark and the second point").show()
        rm.runCommand("Add")
        roi_points = rm.getRoisAsArray()
        for Roi in roi_points:

            xpoints = Roi.getPolygon().xpoints
            ypoints = Roi.getPolygon().ypoints
            print(xpoints, ypoints)

        print('Start Landmark', xpoints[0], ypoints[0])
        fixedpointX = xpoints[0]
        fixedpointY = ypoints[0]
        print('End Landmark', xpoints[1], ypoints[1])
        IJ.makeLine(xpoints[0], ypoints[0], xpoints[1], ypoints[1])
        gui = GenericDialog("Rotation Angle")
        gui.addNumericField("Choose Angle", 15, 0)
        gui.showDialog()
        if gui.wasOKed():

            rotateangle = gui.getNextNumber()
            IJ.run("Rotate...", "angle=" + str(int(float(rotateangle))))

        rm.runCommand("reset")
        overlay = imp.getOverlay()
        rm.runCommand("Add")
        roi_points = rm.getRoisAsArray()

        for Roi in roi_points:
            xpoints = Roi.getPolygon().xpoints
            ypoints = Roi.getPolygon().ypoints
            print(xpoints, ypoints)

        print('Rotated Start Landmark', xpoints[0], ypoints[0])
        print('Rotated End Landmark', xpoints[1], ypoints[1])
        slope = (ypoints[1] - ypoints[0]) / (xpoints[1] - xpoints[0] + 1.0E-20)
        intercept = fixedpointY - slope * fixedpointX
        print(fixedpointX, fixedpointY)
        print('Slope', slope, 'Intercept', intercept)
        XwY0 = -intercept / slope
        YxwY0 = slope * XwY0 + intercept

        XwYmax = (impY - intercept) / slope
        YxwYmax = slope * XwYmax + intercept

        YwX0 = intercept
        XywX0 = (YwX0 - intercept) / slope
        YwXmax = impX * slope + intercept
        XxwXmax = (YwXmax - intercept) / slope
        rm.runCommand("reset")

        if XwY0 > 0:
            lineROIA = Line(fixedpointX, fixedpointY, XwY0, YxwY0)
            lineROIB = Line(fixedpointX, fixedpointY, XwYmax, YxwYmax)
            overlay.add(lineROIA)

            overlay.add(lineROIB)

        if XwY0 < 0:
            lineROIA = Line(fixedpointX, fixedpointY, XywX0, YwX0)
            lineROIB = Line(fixedpointX, fixedpointY, XxwXmax, YwXmax)
            overlay.add(lineROIA)

            overlay.add(lineROIB)

        while cursor.hasNext():
            cursor.fwd()
            X = cursor.getDoublePosition(0)
            Y = cursor.getDoublePosition(1)
            if abs(Y - slope * X - intercept) <= 4:
                cursor.get().set(0)
            else:
                cursor.get().set(1)
        labeling = ops.labeling().cca(maskimage,
                                      StructuringElement.EIGHT_CONNECTED)

        # get the index image (each object will have a unique gray level)
        labelingIndex = labeling.getIndexImg()
        dataImg = ds.create(labelingIndex)
        location = ls.resolve(
            str(savedir) + '/' + file_name + '.' + file_type_image)
        dio.save(dataImg, location)
        imp.close()
Beispiel #21
0
for l in range(0, height):
    for c in range(l + 1, width):
        p1 = pointList[l]
        p2 = pointList[c]
        delta_x = p1.x - p2.x
        delta_y = p1.y - p2.y
        value = math.sqrt((delta_x * delta_x) + (delta_y * delta_y))
        matrix[l][c] = value
        matrix[c][l] = value

nearestNeighborsDist = []
nearestNeighborsInd = []
for l in range(0, width):
    minimum = min(matrix[l])
    index = matrix[l].index(minimum)
    nearestNeighborsDist.append(minimum)
    nearestNeighborsInd.append(index)

RoiManager()
roiManager = RoiManager.getRoiManager()

for i in range(0, width):
    nnI = nearestNeighborsInd[i]
    if (nnI < i and nearestNeighborsInd[nnI] == i):
        continue
    p1 = pointList[i]
    p2 = pointList[nnI]
    roi = Line(p1.x, p1.y, p2.x, p2.y)
    roiManager.addRoi(roi)
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 #23
0
 egfp_imp.setZ(zidx + 1)
 cl_imp.setZ(zidx + 1)
 ip = cl_imp.getProcessor()
 out = MaximumFinder().getMaxima(ip, 10, True)
 centres.append((out.xpoints[0], out.ypoints[0]))
 centre = (out.xpoints[0], out.ypoints[0])
 ring_roi_xs = []
 ring_roi_ys = []
 for theta in range(359):
     #	for theta_idx in range(6):
     #		theta = theta_idx * 60 - 90;
     pt1 = (centre[0] + min_r_pix * math.cos(math.radians(theta)),
            centre[1] + min_r_pix * math.sin(math.radians(theta)))
     pt2 = (centre[0] + max_r_pix * math.cos(math.radians(theta)),
            centre[1] + max_r_pix * math.sin(math.radians(theta)))
     roi = Line(pt1[0], pt1[1], pt2[0], pt2[1])
     egfp_imp.setRoi(roi)
     profile = roi.getPixels()
     projected_im_row.append(max(profile))
     try:
         ring_roi_xs.append(roi.getContainedPoints()[profile.index(
             max(profile))].x)
     except IndexError:
         ring_roi_xs.append(pt2[0])
     try:
         ring_roi_ys.append(roi.getContainedPoints()[profile.index(
             max(profile))].y)
     except IndexError:
         ring_roi_ys.append(pt2[1])
     #print("Max val = " + str(max(profile)));
     egfp_imp.killRoi()
def angle(xy1, xy2):
    diffx = xy2[0] - xy1[0]
    diffy = xy2[1] - xy1[1]
    return math.atan2(diffy, diffx)


def calculate_point(x_orig, y_orig, distance, angle):
    x_new = distance * math.cos(math.radians(angle)) + x_orig
    y_new = (distance * math.sin(math.radians(angle)) - y_orig) * -1
    return (x_new, y_new)


# Defining the boxes

roi1 = Line(point1[0], point1[1], point2[0], point2[1])

upangle = roi1.getAngle() + 90

downangle = roi1.getAngle() - 90

distance = roi1.getLength() / pixelsize

# calculating the coordinates of the box ROIs
starting_upper_point = (calculate_point(point1[0], point1[1], roi_width,
                                        upangle))
starting_lower_point = (calculate_point(point1[0], point1[1], roi_width,
                                        downangle))
end_upper_point = (calculate_point(point2[0], point2[1], roi_width,
                                   roi1.getAngle() + 90))
end_lower_point = (calculate_point(point2[0], point2[1], roi_width,