def delete(imp, roiMan, roiTotal):

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

	if roiMan is not None:
		# Iterate through the ROIs
		for roi in xrange(roiTotal):
			# Select the ROI
			roiMan.select(roi)
			selectRoi = roiMan.getRoi(roi)
			# measure
			analyzer.measure()
			meas = rt.getRowAsString(0)
			newLine = meas.split("	", 1)
			pixels = float(newLine[1])
			totalPixels = totalPixels + pixels
			# Tag the ROI
			IJ.run(imp, "Fill", "slice")
		# end for loop
		return totalPixels
	else:
		return 0
def learn(imp):

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

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

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

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

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

    roiTotal = roiMan.getCount()

    if roiMan is not None:

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

            option = getOptions()

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

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

        return pixelTotal
    else:
        return pixelTotal
Esempio n. 3
0
	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]
Esempio n. 4
0
	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)
def measureROIs(imp, measOpt, thisrt, roiA, backint, doGLCM):    
  """ Cell-wise measurment using ROI array. 
  """
  analObj = Analyzer(imp, measOpt, thisrt)
  for index, r in enumerate(roiA):
    imp.deleteRoi()
    imp.setRoi(r)
    analObj.measure()
    maxint = thisrt.getValue('Max', thisrt.getCounter()-1)
    saturation = 0
    if ( maxint + backint) >= 4095:
      saturation = 1
      if (VERBOSE):
        print 'cell index ', index, 'maxint=', maxint
    thisrt.setValue('CellIndex', thisrt.getCounter()-1, index)
    thisrt.setValue('Saturation', thisrt.getCounter()-1, saturation)
  if (doGLCM):
    imp.deleteRoi()
    measureTexture(imp, thisrt, roiA)
def identifyCoralline(imp):
    # Prepare Roi Manager
    rm = RoiManager.getInstance()
    if rm is not None:
        rm.reset()

    # set results table
    rt = ResultsTable.getResultsTable()

    impTemp = imp.duplicate()
    IJ.run(impTemp, "8-bit", "")  # convert to 8-bit
    impCoralline = TH.whiteThreshold(impTemp)
    impTemp.close()

    IJ.run(impCoralline, "Analyze Particles...",
           "size=10000-Infinity circularity=0-0.50 show=Masks add in_situ")
    analyzer = Analyzer(imp, 1, rt)
    analyzer.measure()
    meas = rt.getRowAsString(0)
    newLine = meas.split("	", 1)
    coralline = float(newLine[1])
    return coralline
else:
  overallSelectionMask = manualMask.copy();

newMask = ops.map(newMask, overallSelectionMask, coherencyMask, andOp);

if IJ.debugMode:
  displays.createDisplay("oriented-mask", ImgPlus(newMask));
  displays.createDisplay("overall-mask", ImgPlus(overallSelectionMask));

### Compute area fraction of oriented regions ###
# Compute area of oriented mask
newMaskImp = ImageJFunctions.wrapUnsignedByte(newMask, "New mask");
newMaskImp.getProcessor().setThreshold(1.0, 1.5, False); # [0.5, 1.0] does not work due to rounding problems
rt = ResultsTable();
analyzer = Analyzer(newMaskImp, Measurements.AREA | Measurements.LIMIT, rt);
analyzer.measure();

# Compute area of overall selection mask 
energyMaskImp = ImageJFunctions.wrapUnsignedByte(overallSelectionMask, "Energy mask");
energyMaskImp.getProcessor().setThreshold(1.0, 1.5, False); # [0.5, 1.0] does not work due to rounding problems
rtEnergy = ResultsTable();
analyzerEnergy = Analyzer(energyMaskImp, Measurements.AREA | Measurements.LIMIT, rtEnergy);
analyzerEnergy.measure();

# Print Area% (through SciJava OUTPUT, see L5)
if IJ.debugMode:
  print("Coherency area: "+str(rt.getValueAsDouble(rt.getColumnIndex("Area"), rt.size()-1)));
  print("Energy area: "+str(rtEnergy.getValueAsDouble(rtEnergy.getColumnIndex("Area"), rtEnergy.size()-1)));

areaCoherency = rt.getValueAsDouble(rt.getColumnIndex("Area"), rt.size()-1);
areaEnergy = rtEnergy.getValueAsDouble(rtEnergy.getColumnIndex("Area"), rtEnergy.size()-1);


            # FINDS THE TISSUE AREA
            img2 = imp.duplicate()
            channels2=ChannelSplitter.split(img2);
            redimg2=channels2[0];
            IJ.run(redimg2, "8-bit", "");
            IJ.setAutoThreshold(redimg2, "Default dark");
            IJ.setThreshold(redimg2,20, 254);
            IJ.run(redimg2, "Convert to Mask", "");
            redimg2.show()
            time.sleep(1)
            rt2 = ResultsTable()
            ta=Analyzer(redimg2,Measurements.AREA|Measurements.LIMIT,rt2)
            ta.measure();
            double=rt2.getColumnAsDoubles(rt2.getColumnIndex("Area"))
            summary["Tissue-area"] =double[0];
            redimg2.changes = False
            redimg2.close()
            	

#    PARTICLE ANALYSIS ETC..
                
            channels = ChannelSplitter.split(imp);
            
            
            
            for i, channel in enumerate(channels):
                IJ.setAutoThreshold(channel,"Default");
                summary[color[i] + "-intensity"] = "NA"
Esempio n. 9
0
	def __fmeasures(self) : 
		self.__Cutoff = float(self.__display4.text)
		nslices = self.__impRes.getImageStackSize() 
		rt = ResultsTable()
		rt.show("RT-"+self.__name)
		if self.__maxfinder : twpoints = TextWindow("points-"+self.__name, "index\tlabel\tname\tx\ty\taxis\tcellw\tcellh", "", 200, 450)
		twlabels = TextWindow("labels-"+self.__name, "index\tlabel\tname\tnpoints", "", 200, 450)

		isres = self.__impRes.getImageStack()
		
		for index in range(1, nslices+1):
			pc = (index*100)/nslices
			IJ.showStatus("Je suis a "+str(pc)+"%")
			self.__impRes.setSlice(index)
			self.__impRes.killRoi()
			roi = self.__listrois[index-1]
			self.__impRes.setRoi(roi)
			analyser= Analyzer(self.__impRes, Analyzer.LABELS+Analyzer.CENTER_OF_MASS+Analyzer.CENTROID+Analyzer.INTEGRATED_DENSITY+Analyzer.MEAN+Analyzer.KURTOSIS+Analyzer.SKEWNESS+Analyzer.MIN_MAX+Analyzer.SLICE+Analyzer.STACK_POSITION+Analyzer.STD_DEV, rt)
			analyser.measure()
			rt.show("RT-"+self.__name)
			
			rect=roi.getBounds()
			ip = self.__impRes.getProcessor()

			xCoord = []
			yCoord = []
			currentPixel = []

			m00 = 0.00
			m10 = 0.00
			m01 = 0.00
			
			mc20 = 0.00
			mc02 = 0.00
			mc11 = 0.00
			mc30 = 0.00
			mc03 = 0.00
			mc21 = 0.00
			mc12 = 0.00
			mc40 = 0.00
			mc04 = 0.00
			mc31 = 0.00
			mc13 = 0.00

			mm20 = 0.00
			mm02 = 0.00
			mm11 = 0.00
			mm30 = 0.00
			mm03 = 0.00
			mm21 = 0.00
			mm12 = 0.00
			mm40 = 0.00
			mm04 = 0.00
			mm31 = 0.00
			mm13 = 0.00
			
			
			#for y in range(rect.y, rect.y+rect.height, 1) :
			#	for x in range(rect.x, rect.x+rect.width, 1) :
			#		xCoord.append(x+0.5)
			#		yCoord.append(y+0.5)
			#		#pixel=ip.getf(x,y)-self.__Cutoff
			#		pixel = ip.getPixelValue(x,y)-self.__Cutoff
			#		if pixel < 0 : pixel = 0
			#		currentPixel.append(pixel)
			#		m00 += currentPixel[-1]
			#		m10 += currentPixel[-1]*xCoord[-1]
			#		m01 += currentPixel[-1]*yCoord[-1]


			#xm = m10/(m00+0.00000001)
			#ym = m01/(m00+0.00000001)

			#xc = rect.width/2.00
			#yc = rect.height/2.00

			#for i in range(rect.width*rect.height) :

			#	xcrel = xCoord[i]-xc
			#	ycrel = yCoord[i]-yc
			
			#	#mc20 += currentPixel[i]*(xCoord[i]-xc)*(xCoord[i]-xc)
			#	#mc02 += currentPixel[i]*(yCoord[i]-yc)*(yCoord[i]-yc)
			#	#mc11 += currentPixel[i]*(xCoord[i]-xc)*(yCoord[i]-yc)
			#	#
			#	#mc30 += currentPixel[i]*(xCoord[i]-xc)*(xCoord[i]-xc)*(xCoord[i]-xc)
			#	#mc03 += currentPixel[i]*(yCoord[i]-yc)*(yCoord[i]-yc)*(yCoord[i]-yc)
			#	#mc21 += currentPixel[i]*(xCoord[i]-xc)*(xCoord[i]-xc)*(yCoord[i]-yc)
			#	#mc12 += currentPixel[i]*(xCoord[i]-xc)*(yCoord[i]-yc)*(yCoord[i]-yc)
			#	#
			#	#mc40 += currentPixel[i]*(xCoord[i]-xc)*(xCoord[i]-xc)*(xCoord[i]-xc)*(xCoord[i]-xc)
			#	#mc04 += currentPixel[i]*(yCoord[i]-yc)*(yCoord[i]-yc)*(yCoord[i]-yc)*(yCoord[i]-yc)
			#	#mc31 += currentPixel[i]*(xCoord[i]-xc)*(xCoord[i]-xc)*(xCoord[i]-xc)*(yCoord[i]-yc)
			#	#mc13 += currentPixel[i]*(xCoord[i]-xc)*(yCoord[i]-yc)*(yCoord[i]-yc)*(yCoord[i]-yc)

			#	mc20 += currentPixel[i]*xcrel*xcrel
			#	mc02 += currentPixel[i]*ycrel*ycrel
			#	mc11 += currentPixel[i]*xcrel*ycrel
				
			#	mc30 += currentPixel[i]*xcrel*xcrel*xcrel
			#	mc03 += currentPixel[i]*ycrel*ycrel*ycrel
			#	mc21 += currentPixel[i]*xcrel*xcrel*ycrel
			#	mc12 += currentPixel[i]*xcrel*ycrel*ycrel
				
			#	mc40 += currentPixel[i]*xcrel*xcrel*xcrel*xcrel
			#	mc04 += currentPixel[i]*ycrel*ycrel*ycrel*ycrel
			#	mc31 += currentPixel[i]*xcrel*xcrel*xcrel*ycrel
			#	mc13 += currentPixel[i]*xcrel*ycrel*ycrel*ycrel

			
			#for i in range(rect.width*rect.height) :
			#	mm20 += currentPixel[i]*(xCoord[i]-xm)*(xCoord[i]-xm)
			#	mm02 += currentPixel[i]*(yCoord[i]-ym)*(yCoord[i]-ym)
			#	mm11 += currentPixel[i]*(xCoord[i]-xm)*(yCoord[i]-ym)

			#	mm30 += currentPixel[i]*(xCoord[i]-xm)*(xCoord[i]-xm)*(xCoord[i]-xm)
			#	mm03 += currentPixel[i]*(yCoord[i]-ym)*(yCoord[i]-ym)*(yCoord[i]-ym)
			#	mm21 += currentPixel[i]*(xCoord[i]-xm)*(xCoord[i]-xm)*(yCoord[i]-ym)
			#	mm12 += currentPixel[i]*(xCoord[i]-xm)*(yCoord[i]-ym)*(yCoord[i]-ym)

			#	mm40 += currentPixel[i]*(xCoord[i]-xm)*(xCoord[i]-xm)*(xCoord[i]-xm)*(xCoord[i]-xm)
			#	mm04 += currentPixel[i]*(yCoord[i]-ym)*(yCoord[i]-ym)*(yCoord[i]-ym)*(yCoord[i]-ym)
			#	mm31 += currentPixel[i]*(xCoord[i]-xm)*(xCoord[i]-xm)*(xCoord[i]-xm)*(yCoord[i]-ym)
			#	mm13 += currentPixel[i]*(xCoord[i]-xm)*(yCoord[i]-ym)*(yCoord[i]-ym)*(yCoord[i]-ym)

			
			
			#xxcVar = mc20/m00
			#yycVar = mc02/m00
			#xycVar = mc11/m00

			#xcSkew = mc30/(m00 * math.pow(xxcVar,(3.0/2.0)))
			#ycSkew = mc03/(m00 * math.pow(yycVar,(3.0/2.0)))

			#xcKurt = mc40 / (m00 * math.pow(xxcVar,2.0)) - 3.0
			#ycKurt = mc04 / (m00 * math.pow(yycVar,2.0)) - 3.0

			#ecc = (math.pow((mc20-mc02),2.0)+(4.0*mc11*mc11))/m00
			
			#xxmVar = mm20/m00
			#yymVar = mm02/m00
			#xymVar = mm11/m00

			#xmSkew = mm30/(m00 * math.pow(xxmVar,(3.0/2.0)))
			#ymSkew = mm03/(m00 * math.pow(yymVar,(3.0/2.0)))

			#xmKurt = mm40 / (m00 * math.pow(xxmVar,2.0)) - 3.0
			#ymKurt = mm04 / (m00 * math.pow(yymVar,2.0)) - 3.0

			#ecm = (math.pow((mm20-mm02),2.0)+(4.0*mm11*mm11))/m00

			#rt.addValue("xxcVar", xxcVar)
			#rt.addValue("yycVar", yycVar)
			#rt.addValue("xycVar", xycVar)

			#rt.addValue("xcSkew", xcSkew)
			#rt.addValue("ycSkew", ycSkew)

			#rt.addValue("xcKurt", xcKurt)
			#rt.addValue("ycKurt", ycKurt)

			#rt.addValue("Ecc", ecc)

			#rt.addValue("xxmVar", xxmVar)
			#rt.addValue("yymVar", yymVar)
			#rt.addValue("xymVar", xymVar)

			#rt.addValue("xmSkew", xmSkew)
			#rt.addValue("ymSkew", ymSkew)

			#rt.addValue("xmKurt", xmKurt)
			#rt.addValue("ymKurt", ymKurt)

			#rt.addValue("Ecm", ecm)

			rt.addValue("roiw", rect.width)
			rt.addValue("roih", rect.height)

			rt.addValue("cellw", self.__ipw[index-1])
			rt.addValue("cellh", self.__iph[index-1])

			self.__impRes.killRoi()

			xCoord[:] = []
			yCoord[:] = []
			currentPixel[:] = []
			points = []
			points[:] = []
			npointsmax = 0
			
			#lab = self.__labels[index-1]
			nameroi = self.__dictCells[index][0]
			lab = self.__dictCells[index][1]

			if self.__maxfinder : 
				self.__impMax.setSlice(index)
				ipmax = self.__impMax.getProcessor()
				for y in range(ipmax.getHeight()) :
					for x in range(ipmax.getWidth()) :
						if ipmax.getPixelValue(x,y) > 0 : 
							twpoints.append(str(index)+"\t"+lab+"\t"+nameroi+"\t"+str(x)+"\t"+str(y)+"\t"+str(self.__cellsrois[index-1][0].getLength())+"\t"+str(self.__ipw[index-1])+"\t"+str(self.__iph[index-1]))
							npointsmax+=1
				rt.addValue("npoints", npointsmax)

			twlabels.append(str(index)+"\t"+lab+"\t"+nameroi+"\t"+str(npointsmax))
			rt.show("RT-"+self.__name)
			
		rt.show("RT-"+self.__name)
	if (gd.wasCanceled()): 
		quit()

	index1 = gd.getNextChoiceIndex()
	index2 = gd.getNextChoiceIndex()
	image1 = WindowManager.getImage(wList[index1])
	image2 = WindowManager.getImage(wList[index2])
	IJ.selectWindow(wList[index1])

	rt = ResultsTable.getResultsTable()
	rt.reset()
	gd = WaitForUserDialog("Pick region with only bleedthrough")
	gd.show()
	al1 = Analyzer(image1)
	theSlice = image1.getSlice()
	al1.measure()
	al1.displayResults()
	theRoi = image1.getRoi()
	al2 = Analyzer(image2)
	image2.setSlice(theSlice)
	image2.setRoi(theRoi)
	al2.measure()
	al2.displayResults()
	gd = WaitForUserDialog("Pick autofluorescent tissue region")
	gd.show()
	al1.measure()
	al1.displayResults()
	theRoi = image1.getRoi()
	image2.setRoi(theRoi)
	al2.measure()
	al2.displayResults()
def run():
    '''This is the main function run when the plugin is called.'''

    #print dir(IJ)
    ip = IJ.getProcessor()

    imp = IJ.getImage()  # get the current Image, which is an ImagePlus object
    #print "imp=", type(imp), imp
    #print dir(imp)

    roi = imp.getRoi()  # get the drawn ROI
    #print "roi=", roi, roi.getClass()

    # check ROI type
    if roi == None:
        gd = GenericDialog("Draw Measurement - Line")
        gd.addMessage("Please draw a straight-line first!")
        gd.showDialog()
        return
        #raise Exception(  "Please draw a line ROI first!" )
    if roi.getTypeAsString() != "Straight Line":
        gd = GenericDialog("Draw Measurement - Line")
        gd.addMessage("Please draw a straight-line first!")
        gd.showDialog()
        return
        #raise Exception(  "Not a Line ROI!  (type="+roi.getTypeAsString()+")"  )

    # Add auto calibration from text file
    if sets.autoupdatecal:

        newcal = imp.getCalibration().copy(
        )  # make a copy of current calibration object

        if MC_DEBUG: print("Assume calibration is a custom function.")
        # call the class' `classObj.cal( ImagePlusObject )` function to get the scale value:
        try:
            calObject = sets.autoupdatecal_name
            calName = calObject.name
            newPixelPerUnit = calObject.cal(imp)
        except AttributeError:
            raise ValueError(
                'This calibration Name value is invalid, please check your Settings.py file!/n/tFor Calibration Number %i, got: `'
                % (CalIdx) + str(cal.names[CalIdx]) +
                '`. Expected a String or a Class instance with ".cal()" method, but got type '
                + str(type(cal.names[CalIdx])) + ' with no ".cal()" method.')
        #end try

        newUnit = calObject.unit
        newAspect = calObject.aspect_ratio

        newPixelWidth = 1. / newPixelPerUnit
        newPixelHeight = newPixelWidth * newAspect

        # the following translated from "Microscope_Scale.java":
        newcal.setUnit(newUnit)
        newcal.pixelWidth = newPixelWidth
        newcal.pixelHeight = newPixelHeight

        imp.setGlobalCalibration(None)
        imp.setCalibration(newcal)  # set the new calibration
        imp.getWindow().repaint()  # refresh the image?

    # Added - add the measurement to the list...
    a = Analyzer(imp)
    a.measure()
    a.displayResults()

    # from ij.measure import ResultsTable
    # rt = ResultsTable.getResultsTable()

    p1 = [int(roi.x1d), int(roi.y1d)]  # point 1 (x,y)
    p2 = [int(roi.x2d), int(roi.y2d)]  # point 2
    #print "DrawMeas(): Line Points: p1=", p1, " & p2=", p2
    pm = midpoint(p1, p2)  # get midpoint coord

    # set ROI params from settings:
    ''' Using new method - used ip.drawLine instead of roi.draw, since roi.draw didn't always apply the line thickness.  Would be best to use the ROI method, in case other types of ROI's could be annotated.
     
    roi.setStrokeWidth( sets.linethickness ) 
    roi.setStrokeColor(  jColor(float(sets.linecolor[0]), float(sets.linecolor[1]), float(sets.linecolor[2]), float(sets.linecolor[3]))  ) 
     
    #roi.drawPixels( ip )   # draw along the ROI - only draws outline unfortunately 
    ip.drawRoi(roi)     # draw the ROI on the image 
    '''

    ip.setLineWidth(int(sets.linethickness))
    ip.setColor(
        jColor(float(sets.linecolor[0]), float(sets.linecolor[1]),
               float(sets.linecolor[2]), float(sets.linecolor[3])))

    #ip.draw(roi)   # changed to ip.drawLine()
    ip.drawLine(int(roi.x1d), int(roi.y1d), int(roi.x2d), int(roi.y2d))
    '''Draw text annotation'''
    unit = imp.getCalibration().getUnit().encode(
        'utf8')  # get the unit as UTF-8 (for \mu)
    #print "Draw_Meas(): Unit (raw) = `", unit,"`", type(unit),
    if unit[0] == u'\xc2': unit = unit[1:]  # strip weird char at start of \mu

    # format of measurement text (eg. 3 decimal points):
    lenstr = "%0.3f" % roi.getLength() + " %s" % (
        unit)  # string to print as length
    print "DrawMeas(): Line length= %s" % lenstr
    #print "x,y=", p2[0], p2[1]
    '''determine position of text from line coords, eg "bottom right" or "top left" etc.   '''
    # y-coord:
    if p2[1] > p1[1]:
        posstr = 'bottom'
    else:
        posstr = 'top'

    # x-coord:
    if p2[0] > p1[0]:
        posstr += ' right'
    else:
        posstr += ' left'

    drawText(lenstr, p2[0], p2[1], position=posstr)

    imp.updateAndDraw()  #update the image
Esempio n. 12
0
    def defaultActionSequence(self):
        """
		Central function (DO NOT OVERWRITE) called if a button is clicked or shortcut called
		It trigger the following actions:
		- getting the current table
		- checking the GUI state (checkboxes, dropdown...)
		- running measurements if measure is selected
		- setting ROI attribute (if roi)
		- incrementing table counter
		- adding image directory and name to table
		- filling columns from GUI state using custom fillTable()
		- switching to next slice
		- displaying the annotation GUI to the front, important to catch next keyboard shortcuts
		"""
        try:
            imp = IJ.getImage()  # get current image
        except:  # no image: just stop the execution then
            return

        # Get current table
        table = getTable()
        table.showRowNumbers(True)

        # Check options, use getCheckboxes(), because the checkbox plugin have other checkboxes
        checkboxes = self.getCheckboxes()

        # Initialize Analyzer
        if self.runMeasure:
            analyzer = Analyzer(imp, table)
            analyzer.setMeasurement(Measurements.LABELS,
                                    False)  # dont add label to table

        # Check if existing roi manager
        rm = RoiManager.getInstance()
        indexes = rm.getSelectedIndexes() if rm else [
        ]  # Check if roi selected

        if indexes:

            # Loop over selected ROI
            for index in indexes:  # set selected features as property of rois

                roi = rm.getRoi(index)
                imp.setRoi(roi)

                # Run measure for the ROI
                if self.runMeasure:  # Automatically increment counter
                    analyzer.measure()  # as selected in Set Measurements

                else:
                    table.incrementCounter(
                    )  # Automatically done if runMeasure

                #table.addValue("Index", table.getCounter() )
                for key, value in getImageDirAndName(imp).iteritems():
                    table.addValue(key, value)

                # Add selected items (implementation-specific)
                self.fillTable(table)

                # Read comment
                stringField = self.getStringFields()[0]
                table.addValue("Comment", stringField.text)

                # Add roi name to the table + set its property
                table.addValue("Roi", roi.getName())  # Add roi name to table
                setRoiProperties(roi, table)

        # No roi selected in the Manager
        else:

            if self.runMeasure:  # also automatically increment counter
                analyzer.measure()  # as selected in Set Measurements

            else:
                table.incrementCounter()  # Automatically done if runMeasure

            #table.addValue("Index", table.getCounter() )
            for key, value in getImageDirAndName(imp).iteritems():
                table.addValue(key, value)

            # Add selected items (implementation-specific)
            self.fillTable(table)

            # Read comment
            stringField = self.getStringFields()[0]
            table.addValue("Comment", stringField.text)

            # Check if an active Roi, not yet present in Manager
            roi = imp.getRoi()

            if roi is not None:
                roi.setPosition(imp)
                rm = getRoiManager()
                rm.addRoi(roi)

                # get back the roi from the manager to set properties
                roiBis = rm.getRoi(rm.getCount() - 1)
                roiName = roiBis.getName()
                table.addValue("Roi", roiName)  # Add roi name to table
                setRoiProperties(roiBis, table)

        title = table.getTitle() if table.getTitle(
        ) else "Annotations"  # getTitle is None for newly generated table
        table.show(title)  # Update table
        #table.updateResults() # only for result table but then addValue does not work !

        # Go to next slice
        doNext = checkboxes[-1].getState()
        if doNext:
            if self.browseMode == "stack":
                nextSlice(imp, self.getSelectedDimension())
            elif self.browseMode == "directory":
                NextImageOpener().run("forward")

        # Bring back the focus to the button window (otherwise the table is in the front)
        if not IJ.getFullVersion().startswith("1.52p"):
            WindowManager.toFront(self)  # prevent some ImageJ bug with 1.52p