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
Beispiel #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]
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
def segmentChannel_Weka(image, **kwargs):
	""" SegmentChannel using a Weka Classification"""
	ch = kwargs['channel']
	if ch > len(image): 
		raise Exception('Expecting at least ' + str(ch) + ' channels. Image has only ' + str(len(imageC)) + ' channel(s)')
	imp = image[ch-1].duplicate()
	ws = WekaSegmentation(imp)	# create an instance
	ws.loadClassifier(kwargs['clspath']) # load classifier
	impProb  = ws.applyClassifier(imp, 0, True)
	impMetaProb = extractChannel(impProb,1,1)
	impMetaProb.setTitle("MetaProb")
	# segmentation
	impBW = threshold(impMetaProb, kwargs['probThr'])
	impMetaProb.show()
	IJ.run("Set Measurements...", " mean center shape area redirect=MetaProb decimal=2");
	
	# particle analysis
	IJ.run(impBW, "Analyze Particles...", "size=10-10000 pixel area circularity=0.00-1.00 display exclude clear stack add");
	rt = Analyzer.getResultsTable()
	validParticles = []
	roim = RoiManager.getInstance()
	if roim == None:
		raise Exception('Fiji error segmentNuclei.py: no RoiManager!')
	if roim.getCount() > 0:
		rois = roim.getRoisAsArray()
	else:
		IJ.log("# particles = 0")
		return impMetaProb, impBW, None, None
	X = rt.getColumn(rt.getColumnIndex("XM"))
	Y = rt.getColumn(rt.getColumnIndex("YM"))
	Mean = rt.getColumn(rt.getColumnIndex("Mean"))
	Circ = rt.getColumn(rt.getColumnIndex("Circ."))
	Area = rt.getColumn(rt.getColumnIndex("Area"))
	print "# particles = " + str(len(Mean))
	nValid = 0
	for i in range(len(Mean)):
		valid = (Mean[i]>kwargs['minProb']) and (Circ[i]<kwargs['maxCirc']) # filter particles post detection
		if(valid):
			validParticles.append([i, X[i], Y[i], Mean[i]])
	print validParticles
	IJ.log("# valid particles = %d " % len(validParticles))
	# sort particles according to Mean
	validParticlesSorted = sorted(validParticles, key=itemgetter(3))
	# only keep the three with the largest Mean
	validParticles = validParticlesSorted[-int(kwargs["nrPart"]):]
    #random.shuffle(validParticles)
	IJ.log("# valid particles = %d " % len(validParticles))
	if len(validParticles) == 0:
		validParticles = None
	return impMetaProb, impBW, validParticles, rois
Beispiel #7
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)
  overallSelectionMask = ops.map(overallSelectionMask, energyMask, invertedManualMask, andOp);
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);
# IJ BAR: https://github.com/tferr/Scripts#scripts
#
# Imports numeric values copied to the clipboard into the Results table. Useful, since
# BARs that analyze tabular data can only read values from the main IJ "Results" table
#
# Requirements: Requires BAR_-XX.jar to be installed in the plugins folder of IJ
#
# NB: When copying data from withing IJ (e.g., lists from histograms or plot profiles),
# Use Edit>Options>Input/Output... to specify if column headers/row numbers should be
# copied to the clipboard


import os, sys, tempfile
from bar import Utils as barUtils
from ij import IJ
from ij.plugin.filter import Analyzer
import ij.measure.ResultsTable as RT


fd, path = tempfile.mkstemp()
try:
    os.write(fd, barUtils.getClipboardText())
    os.close(fd)
    rt = RT.open(path) #IOException if getClipboardText()==""
    if Analyzer.resetCounter():
        rt.show("Results")
except:
    IJ.error("Could not place clipboard into Results table.")
finally:
    os.remove(path)
Beispiel #10
0
 nucMaskIp2 = ImagePlus("Masked Nuclei", nucMaskIp.getStack().getProcessor(1))
 nucMaskIp2.setStack(nucMaskStack2)
 #This calculates the voronoi diagram
 IJ.run(nucMaskIp2, "8-bit", "")
 nucMaskStack2 = nucMaskIp2.getStack()
 IJ.run(nucMaskIp2, "Close", "stack")
 IJ.run(nucMaskIp2, "Invert", "stack")
 IJ.run(nucMaskIp2, "Voronoi", "stack")
 for proc in (nucMaskStack2.getProcessor(n) for n in range(1, nucMaskStack2.size() + 1)): proc.threshold(0)
 IJ.run(nucMaskIp2, "Invert", "stack")
 #This burns the boundary lines of the voronoi diagram into the nuclear mask image, completing the segmentation
 nucAnalyzeIp = ImageCalculator().run("AND create stack", nucMaskIp, nucMaskIp2)
 nucAnalyzeIp.show()
 #This measures the nuclei
 IJ.run("Set Measurements...", "area mean centroid fit shape feret's stack decimal=3")
 Analyzer.setRedirectImage(nucIpForMeasure)
 IJ.run(nucAnalyzeIp, "Analyze Particles...", "display stack")
 rt = ResultsTable.getResultsTable()
 groupString = '_'.join("%s=%s" % (key,''.join(val)) for (key,val) in zip(groupBy, outerPairs))
 rt.saveAs(outputFolder +r"/nuclei_" + groupString + ".csv")
 IJ.run("Clear Results")
 rt = ResultsTable.getResultsTable()
 #This links nuclei to their respective cardiomyocyte (if present). The cardiomyocyte count mask image
 #has each pixel within a given cardiomyocyte set to its id number, so the minimum value for a nucleus roi in the cardiomyocyte
 #count mask image will be that cardiomyocyte's id number if the nucleus is 100% contained within a cardiomyocyte
 #or zero if not
 Analyzer.setRedirectImage(cmIp)
 IJ.run("Set Measurements...", "min decimal=3")
 IJ.run(nucAnalyzeIp, "Analyze Particles...", "display stack")
 rt.saveAs(outputFolder +r"/nucleilink_" + groupString + ".csv")
 IJ.run("Clear Results")



            # 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");
Beispiel #12
0
def getMeasurementInt() :
    """returns the int value of the measurements setting, made as a hack to translate a set of checkboxes to its corresponding number"""
    a = Analyzer()
    i = a.getMeasurements()
    return i
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
Beispiel #14
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
def Measurements(channels, timelist, dirs, parameters):
    """ Takes measurements of weka selected ROIs in a generated aligned image stack. """
	
    # Set desired measurements. 
    an = Analyzer()
    an.setMeasurements(an.AREA + an.MEAN + an.MIN_MAX + an.SLICE)

    # Opens raw-projections as stack.
    test = IJ.run("Image Sequence...",
	              "open=" + dirs["Aligned_All"]
	              + " number=400 starting=1 increment=1 scale=400 file=.tif sort")

    # Calls roimanager.
    rm = RoiManager.getInstance()	
    total_rois = rm.getCount()

    # Deletes artefact ROIs (too large or too small). 
    imp = WindowManager.getCurrentImage()
    for roi in reversed(range(total_rois)):
        rm.select(roi)
        size = imp.getStatistics().area		
        if size < int(float(parameters["cell_min"])):
            rm.select(roi)
            rm.runCommand('Delete')
        elif size > int(float(parameters["cell_max"])):
            rm.select(roi)
            rm.runCommand('Delete')
        else:
            rm.runCommand("Deselect")

    # Confirm that ROI selection is Ok (comment out for headless run).
    WaitForUserDialog("ROI check", "Control ROI selection, then click OK").show() 
	
    # Measure each ROI for each channel.
    imp = WindowManager.getCurrentImage()
    rm.runCommand("Select All")	
    rm.runCommand("multi-measure measure_all One row per slice")		
	
    # Close.
    imp = WindowManager.getCurrentImage()
    imp.close()

    # Get measurement results.
    rt = ResultsTable.getResultsTable()
    Area = rt.getColumn(0)
    Mean = rt.getColumn(1)
    Slice = rt.getColumn(27)
	
    # Removes (and counts) artefact ROIs (redundant)
    # Area indices without outliers
    Area_indices = [index for (index, value) in enumerate(Area, start=0)
	                if value > 0 and value < 9999999]
	
    # Mean without outliers from area (redundant)
    Filtered_mean = [Mean[index] for index in Area_indices]
    Filtered_slice = [Slice[index] for index in Area_indices]

    # Number of cell selections.
    Cell_number = Filtered_slice.count(1.0)
    rm = RoiManager.getInstance()
    print "Number of selected cells: ", Cell_number
    print "Total number of selections: ", rm.getCount()

    Cells = [ Filtered_mean [x : x + Cell_number]
	          for x in xrange (0, len(Filtered_mean), Cell_number) ]
              	
    Cells_indices = [ index for (index, value) in enumerate(Cells) ]
	
    time = [ x for item in timelist for x in repeat(item, Cell_number) ]
    time = [ time [x : x + Cell_number] for x in xrange (0, len(time), Cell_number) ]
	
    Slices = [ Filtered_slice [x : x + Cell_number]
	           for x in xrange (0, len(Filtered_slice), Cell_number) ]
	
    # Lists IDD, IDA + IAA if 3ch.
    if channels == 3:
        IDD_list = [ Cells [index] for index in Cells_indices [0::int(channels)] ]
        IDA_list = [ Cells [index] for index in Cells_indices [1::int(channels)] ]    
        IAA_list = [ Cells [index] for index in Cells_indices [2::int(channels)] ]
        
        raw_data = {"IDD" : IDD_list, "IDA" : IDA_list, "IAA" : IAA_list,
                    "Cell_num" : Cell_number, "Slices" : Slices,
                    "Time" : time
                    }
	
	
    elif channels == 2:
        IDD_list = [ Cells [index] for index in Cells_indices [0::int(channels)] ]
        IDA_list = [ Cells [index] for index in Cells_indices [1::int(channels)] ]
        
        raw_data = {"IDD": IDD_list, "IDA" : IDA_list,
                    "Cell_num" : Cell_number, "Slices" : Slices,
                    "Time" : time
                    }

    return raw_data
Beispiel #16
0
def processImages(cfg, wellName, wellPath, images):

    stats = [[[dict() for t in range(cfg.getValue(ELMConfig.numT))] for z in range(cfg.getValue(ELMConfig.numZ))] for c in range(cfg.getValue(ELMConfig.numChannels))]
    times = {}
    for c in range(0, cfg.getValue(ELMConfig.numChannels)):
        chanStr = 'ch%(channel)02d' % {"channel" : c};
        chanName = cfg.getValue(ELMConfig.chanLabel)[c]

        # Set some config based upon channel
        if (cfg.getValue(ELMConfig.chanLabel)[c] in cfg.getValue(ELMConfig.chansToSkip)):
            continue
        if (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.BRIGHTFIELD):
            minCircularity = 0.001 # We want to identify one big cell ball, so ignore small less circular objects
            if cfg.params[ELMConfig.imgType] == "png":
                minSize = 5;
            else:
                minSize = 500
        elif (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.BLUE) \
                or (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.RED) \
                or (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.GREEN): #
            minCircularity = 0.001
            minSize = 5
        elif (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.YELLOW):
            minCircularity = 0.001
            minSize = 5

        # Process images in Z stack
        for z in range(0, cfg.getValue(ELMConfig.numZ)):
            zStr = cfg.getZStr(z);
            for t in range(0, cfg.getValue(ELMConfig.numT)):
                tStr = cfg.getTStr(t)
                if (cfg.getValue(ELMConfig.imgType) == "png"):
                    # Brightfield uses the whole iamge
                    if (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.BRIGHTFIELD):
                        currIP = IJ.openImage(images[c][z][t][0])
                    else: # otherwise, we'll plit off channels
                        chanIdx = 2
                        if (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.RED):
                            chanIdx = 0
                        elif (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.GREEN):
                            chanIdx = 1;
                        img = IJ.openImage(images[c][z][t][0])
                        imgChanns = ChannelSplitter.split(img);
                        img.close()
                        currIP = imgChanns[chanIdx];
                else:
                    currIP = IJ.openImage(images[c][z][t][0])
                resultsImage = currIP.duplicate()
                dbgOutDesc = wellName + "_" + zStr + "_" + chanStr + "_" + tStr
                if (cfg.getValue(ELMConfig.numT) > 1):
                    outputPath = os.path.join(wellPath, "images") 
                    if not os.path.exists(outputPath):
                        os.makedirs(outputPath)
                else:
                    outputPath = wellPath

                if cfg.getValue(ELMConfig.debugOutput):
                    WindowManager.setTempCurrentImage(currIP)
                    IJ.saveAs('png', os.path.join(outputPath, "Orig_" + dbgOutDesc +  ".png"))

                # We need to get to a grayscale image, which will be done differently for different channels
                startTime = time.time()
                currIP = ELMImageUtils.getThresholdedMask(currIP, c, z, t, chanName, cfg, outputPath, dbgOutDesc)
                endTime = time.time()
                if not 'grayscale' in times:
                    times['grayscale'] = []
                times['grayscale'].append(endTime-startTime)

                if (not currIP):
                    resultsImage.close()
                    stats[c][z][t][ELMConfig.UM_AREA] = []
                    continue
                
                startTime = time.time()
                # Create a table to store the results
                table = ResultsTable()
                # Create a hidden ROI manager, to store a ROI for each blob or cell
                #roim = RoiManager(True)
                # Create a ParticleAnalyzer
                measurements = Measurements.AREA + Measurements.MEAN + Measurements.STD_DEV + Measurements.MIN_MAX + Measurements.CENTROID + Measurements.RECT + Measurements.ELLIPSE
                paFlags = ParticleAnalyzer.IN_SITU_SHOW | ParticleAnalyzer.SHOW_MASKS | ParticleAnalyzer.CLEAR_WORKSHEET
                pa = ParticleAnalyzer(paFlags, measurements, table, minSize, Double.POSITIVE_INFINITY, minCircularity, 1.0)

                #pa.setHideOutputImage(True)
                
                # The Result image is copied when CurrIP can still have calibration from loading
                # We want the output to be in terms of pixels, for ease of use, so adjust calibration
                resultsImage.setCalibration(currIP.getCalibration())
                Analyzer.setRedirectImage(resultsImage)
                if not pa.analyze(currIP):
                    print "There was a problem in analyzing", currIP
        
                endTime = time.time()
                if not 'pa' in times:
                    times['pa'] = []
                times['pa'].append(endTime-startTime)
                #for i in range(0, roim.getCount()) :
                #    r = roim.getRoi(i);
                #    r.setColor(Color.red)
                #    r.setStrokeWidth(2)
                
                # The measured areas are listed in the first column of the results table, as a float array:
                newAreas = []
                maxArea = 0
                if table.getColumn(ResultsTable.AREA):
                    for pixArea in table.getColumn(ResultsTable.AREA):
                        a = pixArea * cfg.getValue(ELMConfig.pixelHeight) * cfg.getValue(ELMConfig.pixelWidth)
                        newAreas.append(a)
                        if (a > maxArea):
                            maxArea = a
                        
                # Threshold areas
                idxToRemove = set()
                if cfg.hasValue(ELMConfig.areaMaxPercentThreshold):
                    areaPercentThresh = cfg.getValue(ELMConfig.areaMaxPercentThreshold)
                    for i in range(0,len(newAreas)):
                        if newAreas[i] < (areaPercentThresh * maxArea):
                            idxToRemove.add(i)
                if cfg.hasValue(ELMConfig.areaAbsoluteThreshold):
                    areaAbsoluteThresh = cfg.getValue(ELMConfig.areaAbsoluteThreshold)
                    for i in range(0,len(newAreas)):
                        if newAreas[i] < areaAbsoluteThresh:
                            idxToRemove.add(i)

                for i in sorted(idxToRemove, reverse=True):
                    del newAreas[i]
                
                stats[c][z][t][ELMConfig.UM_AREA] = newAreas
                centroidX = []
                centroidY = []
                roiX = []
                roiY = []
                roiWidth = []
                roiHeight = []
                rArea = []
                # Store all of the other data
                for col in range(0,table.getLastColumn()):
                    newData = table.getColumn(col)
                    if not newData is None:
                        if col == ResultsTable.X_CENTROID:
                            for idx in idxToRemove:
                                centroidX.append(newData[idx])
                        if col == ResultsTable.Y_CENTROID:
                            for idx in idxToRemove:
                                centroidY.append(newData[idx])
                        if col == ResultsTable.ROI_X:
                            for idx in idxToRemove:
                                roiX.append(int(newData[idx]))
                        if col == ResultsTable.ROI_Y:
                            for idx in idxToRemove:
                                roiY.append(int(newData[idx]))
                        if col == ResultsTable.ROI_WIDTH:
                            for idx in idxToRemove:
                                roiWidth.append(int(newData[idx]))
                        if col == ResultsTable.ROI_HEIGHT:
                            for idx in idxToRemove:
                                roiHeight.append(int(newData[idx]))
                        if col == ResultsTable.AREA:
                            for idx in idxToRemove:
                                rArea.append(newData[idx])
                        
                        for i in sorted(idxToRemove, reverse=True):
                            del newData[i]
                    stats[c][z][t][table.getColumnHeading(col)] = newData

                IJ.saveAs('png', os.path.join(outputPath, "PreFiltered_Segmentation_" + dbgOutDesc + "_particles.png"))

                # Remove the segmentation masks for the objects removed
                currProcessor = currIP.getProcessor()
                ff = FloodFiller(currProcessor)
                currIP.getProcessor().setValue(0)
                calib = resultsImage.getCalibration()
                sortedAreaIndices = [i[0] for i in sorted(enumerate(rArea), key=lambda x:x[1])]
                for idx in range(0, len(sortedAreaIndices)):
                    i = sortedAreaIndices[idx]
                    centX = int(calib.getRawX(centroidX[i]))
                    centY = int(calib.getRawY(centroidY[i]))

                    # Since the centroid isn't guaranteed to be part of the blob
                    # search around until an active pixel is found
                    found = False
                    halfWidth = min([roiHeight[i], roiWidth[i]])
                    for offset in range(0,halfWidth):
                        if found:
                            break
                        for x in range(centX-offset,centX+offset+1):
                            if found:
                                break
                            for y in range(centY-offset,centY+offset+1):
                                if not currProcessor.getPixel(x,y) == 0x0:
                                    found = True
                                    finalX = x
                                    finalY = y
                                    break
                    if not found:
                        print "\t\tZ = " + str(z) + ", T = " + str(t) +  ", chan " + chanName + ": ERROR: Never found active pixel for filtered blob, centroid: " + str(centX) + ", " + str(centY)
                    else:
                        currProcessor.setRoi(roiX[i], roiY[i], roiWidth[i], roiHeight[i])
                        ff.fill8(finalX,finalY)
                        #IJ.saveAs('png', os.path.join(outputPath, "Segmentation_" + dbgOutDesc + "_" + str(idx) + ".png"))
                    
                    
                #outImg = pa.getOutputImage()
                IJ.saveAs('png', os.path.join(outputPath, "Segmentation_" + dbgOutDesc + "_particles.png"))
                
                if cfg.hasValue(ELMConfig.createSegMask) and cfg.getValue(ELMConfig.createSegMask) == True:
                    # Create segmentation mask
                    segMask = currIP.duplicate()
                    segMask.setTitle("SegMask_" + dbgOutDesc)
                    # Iterate by smallest area first
                    #  We are more likely to correctly label small areas
                    if len(newAreas) > 0:
                        segProcessor = segMask.getProcessor()
                        if (len(newAreas) > 255):
                            segProcessor = segProcessor.convertToShort(True)
                            segMask.setProcessor(segProcessor)
                        ff = FloodFiller(segProcessor)
                        sortedAreaIndices = [i[0] for i in sorted(enumerate(stats[c][z][t]['Area']), key=lambda x:x[1])]
                        for idx in range(0, len(sortedAreaIndices)):
                            row = sortedAreaIndices[idx]
                            centX = int(stats[c][z][t]['X'][row])
                            centY = int(stats[c][z][t]['Y'][row])
                            roiX = int(stats[c][z][t]['BX'][row])
                            roiY = int(stats[c][z][t]['BY'][row])
                            roiWidth = int(stats[c][z][t]['Width'][row])
                            roiHeight = int(stats[c][z][t]['Height'][row])
                            area = stats[c][z][t]['Area'][row]
                            halfRoiHeight = roiHeight/2 + 1
                            halfRoiWidth = roiWidth/2 + 1  
                            # Since the centroid isn't guaranteed to be part of the blob
                            # search around until an active pixel is found
                            found = False
                            for xOffset in range(0,halfRoiWidth):
                                if found:
                                    break
                                for yOffset in range(0, halfRoiHeight):
                                    if found:
                                        break
                                    for x in range(centX-xOffset,centX+xOffset+1):
                                        if found:
                                            break
                                        for y in range(centY-yOffset,centY+yOffset+1):
                                            # original image and this image for masked pixel
                                            # By checking original image, we avoid confusion with a label of 255
                                            if segProcessor.getPixel(x,y) == 255 and currProcessor.getPixel(x,y) == 255:
                                                found = True
                                                finalX = x
                                                finalY = y
                                                break
                            if not found:
                                print "\t\tZ = " + str(z) + ", T = " + str(t) +  ", chan " + chanName + ": ERROR: Never found active pixel for seg mask, centroid, roi, area (px): " \
                                    + str(centX) + ", " + str(centY) + ", " + str(roiX) + ", " + str(roiY) + ", " + str(roiWidth) + ", " + str(roiHeight) + ", " + str(area)
                            else:
                                segProcessor.setRoi(roiX, roiY, roiWidth, roiHeight)
                                segProcessor.setColor(row + 1)
                                ff.fill8(finalX,finalY)
                    
                    lut = LutLoader.openLut(cfg.getValue(ELMConfig.lutPath))
                    segMask.setLut(lut)
                    WindowManager.setTempCurrentImage(segMask);
                    IJ.saveAs('png', os.path.join(outputPath, "SegMask_" + dbgOutDesc + "_particles.png"))
                

                startTime = time.time()

                width = currIP.getWidth();
                height = currIP.getHeight();
                overlayImage = resultsImage.duplicate()
                overlayImage.setTitle("Overlay_" + dbgOutDesc + "_particles")
                if not overlayImage.getType() == ImagePlus.COLOR_RGB:
                    imgConvert = ImageConverter(overlayImage)
                    imgConvert.convertToRGB() 
                overlayProcessor = overlayImage.getProcessor()
                currProcessor = currIP.getProcessor()

                if (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.BRIGHTFIELD):
                    maskColor = 0x0000ff00
                elif (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.YELLOW):
                    maskColor = 0x000000ff
                elif (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.RED):
                    maskColor = 0x0000ff00
                elif (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.GREEN):
                    maskColor = 0x00ff0000
                elif (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.BLUE):
                    maskColor = 0x00ffff00

                for x in range(0, width):
                    for y in range(0,height):
                        currPix = currProcessor.getPixel(x,y);
                        if not currPix == 0x00000000:
                            overlayProcessor.putPixel(x, y, maskColor)
                            
                endTime = time.time()
                if not 'overlay' in times:
                    times['overlay'] = []
                times['overlay'].append(endTime-startTime)
                
                WindowManager.setTempCurrentImage(overlayImage);
                IJ.saveAs('png', os.path.join(outputPath, "Overlay_" + dbgOutDesc + "_particles.png"))

                #currIP.hide()
                currIP.close()
                resultsImage.close()

    timesAvg = {}
    for key in times:
        timeList = times[key]
        timesAvg[key] = sum(timeList) / len(timeList);
    print("processImage times " + str(timesAvg))
    return stats
def main():

    #------------------------------
    # 			MAIN
    #------------------------------

    imp_name = imp.getTitle()
    imp_name, ext = os.path.splitext(imp_name)

    models, channel_names, prob_threshs, nms_threshs = [], [], [], []
    if stardist_membrane_enabled:
        models.append(stardist_membrane)
        channel_names.append('Membrane')
        prob_threshs.append(prob_thresh_membrane)
        nms_threshs.append(nms_thresh_membrane)
    if stardist_dna_enabled:
        models.append(stardist_dna)
        channel_names.append('DNA')
        prob_threshs.append(prob_thresh_dna)
        nms_threshs.append(nms_thresh_dna)

    if len(models) == 0:
        return error("no stardist model enabled")

    if tracking_channel not in channel_names:
        return error("channel %s cannot be tracked, must be one of %s" %
                     (tracking_channel, channel_names))

    n_channels = imp.getNChannels()
    n_frames = imp.getNFrames()
    is_hyperstack = n_channels > 1
    if n_frames < 2:
        return error("input must be a timelapse")
    if n_channels != len(models):
        return error(
            "input image has %d channels, but %d stardist model(s) enabled" %
            (n_channels, len(models)))

    export_calibration(imp, save_path(save_dir, imp_name, 'calibration.json'))

    channel_imps = ChannelSplitter.split(imp)

    args = zip(channel_names, channel_imps, models, prob_threshs, nms_threshs)

    if tracking_channel == 'Membrane':
        args = reversed(args)  # tracking_channel must come last

    params = {}
    params['modelChoice'] = "Model (.zip) from File"
    params['outputType'] = "ROI Manager"
    # params['roiPosition'] = "Automatic" # doesn't work because single channels are fed to StarDist, but result may be displayed on hyperstack
    params['roiPosition'] = "Hyperstack" if n_channels > 1 else "Stack"

    print "\n===============================\n"
    for channel_name, channel, model, prob_thresh, nms_thresh in args:
        params['input'] = channel
        params['modelFile'] = model.getAbsolutePath()
        params['probThresh'] = prob_thresh
        params['nmsThresh'] = nms_thresh

        # print 'StarDist', channel_name, ':', params, '\n'
        command.run(StarDist2D, False, params).get()
        rename_rois(rm, is_hyperstack)
        rm.runCommand(
            "Save",
            save_path(save_dir, imp_name,
                      'rois_%s.zip' % channel_name.lower()))
        export_rois(
            rm, is_hyperstack,
            save_path(save_dir, imp_name,
                      'rois_%s.json' % channel_name.lower()))

    assert channel_name == tracking_channel

    # backup global user-chosen measurements
    measurements = Analyzer.getMeasurements()
    # set needed measurements
    Analyzer.setMeasurements(Measurements.AREA + Measurements.CENTER_OF_MASS +
                             Measurements.STACK_POSITION)
    # create measurements table
    rm.runCommand(imp, "Measure")
    # restore global user-chosen measurements
    Analyzer.setMeasurements(measurements)

    # close/hide measurements table
    results_window = ResultsTable.getResultsWindow()
    results_window.close(False)
    # results_window.setVisible(False)

    # Remove overlay if any.
    imp.setOverlay(None)

    # Get results table.
    results_table = ResultsTable.getResultsTable()
    # print results_table

    # Create TrackMate instance.
    trackmate = create_trackmate(imp, results_table, frame_link_dist,
                                 gap_close_dist, seg_split_dist)

    #-----------------------
    # Process.
    #-----------------------

    ok = process(trackmate)
    if not ok:
        sys.exit(str(trackmate.getErrorMessage()))

    #-----------------------
    # Display results.
    #-----------------------

    # TODO: close trackmate gui?

    # Create the GUI and let it control display of results.
    display_results_in_GUI(trackmate, imp)

    color_and_export_rois_by_track(
        trackmate, rm,
        save_path(save_dir, imp_name,
                  'tracks_%s.csv' % tracking_channel.lower()))
ws = WekaSegmentation(imp)  # create an instance
ws.loadClassifier(classifierPath) # load classifier
impProb = ws.applyClassifier(imp, 0, True)
#impProb.show()
impMetaProb = extractChannel(impProb,1,1)
impMetaProb.setTitle("MetaProb")

# segmentation
impBW = threshold(impMetaProb,0.6)
impMetaProb.show()
IJ.run("Set Measurements...", " mean center shape area redirect=MetaProb decimal=2");
impBW.show()

# particle analysis
IJ.run("Analyze Particles...", "size=10-10000 pixel area circularity=0.00-1.00 display exclude clear stack add");
rt = Analyzer.getResultsTable()
validParticles = []
if(rt.getColumnIndex("XM")==-1):
  print "# particles = 0"
else:
  X = rt.getColumn(rt.getColumnIndex("XM"))
  Y = rt.getColumn(rt.getColumnIndex("YM"))
  Mean = rt.getColumn(rt.getColumnIndex("Mean"))
  Circ = rt.getColumn(rt.getColumnIndex("Circ."))
  Area = rt.getColumn(rt.getColumnIndex("Area"))
  print "# particles = " + str(len(Mean))
  for i in range(len(Mean)):
    valid = (Mean[i]>0.8) and (Circ[i]<0.8)   # filter particles post detection
    if(valid):
      validParticles.append(i)
Beispiel #19
0
def setMeasurementInt(i) :
    """sets the measurements setting to the int value i, made as a hack to translate an number to its corresponding checkboxes"""
    a = Analyzer()
    a.setMeasurements(i)
show = sys.argv[ -8 ]
display_results = jython_utils.asbool( sys.argv[ -7 ] )
all_results = jython_utils.asbool( sys.argv[ -6 ] )
exclude_edges = jython_utils.asbool( sys.argv[ -5 ] )
include_holes = jython_utils.asbool( sys.argv[ -4 ] )
tmp_output_path = sys.argv[ -3 ]
output_datatype = sys.argv[ -2 ]
results_path = sys.argv[ -1 ]

# Open the input image file.
input_image_plus = IJ.openImage( input )

# Create a copy of the image.
input_image_plus_copy = input_image_plus.duplicate()
image_processor_copy = input_image_plus_copy.getProcessor()
analyzer = Analyzer( input_image_plus_copy )

try:
    # Set binary options.
    options = jython_utils.get_binary_options( black_background=black_background )
    IJ.run( input_image_plus_copy, "Options...", options )

    # Convert image to binary if necessary.
    if not image_processor_copy.isBinary():
        # Convert the image to binary grayscale.
        IJ.run( input_image_plus_copy, "Make Binary", "" )

    # Set the options.
    options = [ 'size=%s' % size ]
    circularity_str = '%.3f-%.3f' % ( circularity_min, circularity_max )
    options.append( 'circularity=%s' % circularity_str )
Beispiel #21
0
# IJ BAR: https://github.com/tferr/Scripts#scripts
#
# Imports numeric values copied to the clipboard into the Results table. It is
# now deprecated. It was of utility prior to BAR v1.1.7, when BARs that analyzed
# tabular data could only read values from the main IJ "Results" table. It is
# included here as a programming example.
#
# Requirements: Requires BAR_-XX.jar to be installed in the plugins folder of IJ
#
# NB: When copying data from withing IJ (e.g., lists from histograms or plot profiles),
# Use Edit>Options>Input/Output... to specify if column headers/row numbers should be
# copied to the clipboard

import os, tempfile
from bar import Utils as barUtils
from ij import IJ
from ij.plugin.filter import Analyzer
import ij.measure.ResultsTable as RT

fd, path = tempfile.mkstemp()
try:
    os.write(fd, barUtils.getClipboardText())
    os.close(fd)
    rt = RT.open(path)  #IOException if getClipboardText()==""
    if Analyzer.resetCounter():
        rt.show("Results")
except:
    IJ.showMessage("Could not place clipboard into Results table.")
finally:
    os.remove(path)
	gd.showDialog()

	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)
Beispiel #23
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)
show = sys.argv[-8]
display_results = sys.argv[-7] == "yes"
all_results = sys.argv[-6] == "yes"
exclude_edges = sys.argv[-5] == "yes"
include_holes = sys.argv[-4] == "yes"
output_filename = sys.argv[-3]
output_datatype = sys.argv[-2]
results_path = sys.argv[-1]

# Open the input image file.
input_image_plus = IJ.openImage(input_file)

# Create a copy of the image.
input_image_plus_copy = input_image_plus.duplicate()
image_processor_copy = input_image_plus_copy.getProcessor()
analyzer = Analyzer(input_image_plus_copy)

# Set binary options.
options_list = OPTIONS
if black_background:
    options_list.append("black")
options = " ".join(options_list)
IJ.run(input_image_plus_copy, "Options...", options)

if not image_processor_copy.isBinary():
    # Convert the image to binary grayscale.
    IJ.run(input_image_plus_copy, "Make Binary", "")

# Set the options.
options = ['size=%s' % size]
circularity_str = '%.3f-%.3f' % (circularity_min, circularity_max)
On my version of ImageJ (1.52n99) 2019-06-15 setting
res.showRowNumbers() as True or False made no difference

"""
from ij.measure import ResultsTable
from ij import IJ
from ij.plugin.filter import Analyzer
import jmFijiGen as jmg

# start cean
IJ.run("Close All")
jmg.close_open_non_image_window("Results")
jmg.close_open_non_image_window("ROI Manager")

# open our image
imp = IJ.openImage("http://imagej.nih.gov/ij/images/blobs.gif")
Analyzer.setOption("BlackBackground", True)
imp.show()
IJ.run("Convert to Mask")
imp.show()
IJ.run("Set Measurements...",
       "area perimeter shape display redirect=None decimal=3")
IJ.run("Analyze Particles...",
       "size=20-Infinity circularity=0.2-1.00 display exclude clear add")
# Note that this showed the result numbers independent of T/F below
res = ResultsTable.getResultsTable()
res.showRowNumbers(True)
res.updateResults()
print("ImageJ version " + IJ.getFullVersion())
impSub.show()
IJ.selectWindow("Result")
IJ.run("Close")
IJ.selectWindow("Sub")
imp=WM.getCurrentImage()
imp.setTitle(strName+"-acf")
imp.show()

centX = ip.width/2
centY = ip.height/2
top = centX-halfWidth
left = centY-halfWidth
IJ.makeRectangle(top,left,2*halfWidth,2*halfWidth)
IJ.run("Crop")
IJ.setThreshold(0.65, 1.00)
Analyzer.setOption("BlackBackground", False)
if bMakeBinary:
  IJ.run("Make Binary")
  IJ.run("Convert to Mask")
  IJ.run("Set Measurements...", "area centroid redirect=None decimal=3")
  IJ.run("Analyze Particles...", "display exclude clear include")
  rt = ResultsTable.getResultsTable()
  nMeas = rt.getCounter()
  print(nMeas)
  cntX  = rt.getColumn(ResultsTable.X_CENTROID)
  cntY  = rt.getColumn(ResultsTable.Y_CENTROID)
  cntA  = rt.getColumn(ResultsTable.AREA)
  # find the center - will be closest to half width
  fHw = float(halfWidth)
  minDelta = 1000000.
  X0 = 0.
Beispiel #27
0
from ij import IJ
from ij.gui import OvalRoi
from ij.plugin.frame import RoiManager
from ij.plugin.filter import Analyzer
from ij.measure import Measurements, ResultsTable

imp = IJ.getImage()  
rm = RoiManager()  # instantiate manager # throws exception if it doesn't exist
#rm = RoiManager.getInstance() # if manager exists 
 
bright_roi = OvalRoi(118,94,12,12); # define and add ROI
imp.setRoi(bright_roi)  # make active on image
rm.addRoi(bright_roi)  # add
#rm.select(0) # select the ROI

dark_roi = OvalRoi(138,144,12,12)
imp.setRoi(dark_roi)  # make active on image
rm.addRoi(dark_roi)  # add

rm.runCommand(imp,"Measure")		# this will create a new results table
rm.runCommand(imp,"Show All")		# show all ROI
rt = Analyzer.getResultsTable()		

bright_mean = rt.getValueAsDouble(rt.getColumnIndex("Max"),0)
dark_mean = rt.getValueAsDouble(rt.getColumnIndex("Mean"),1)
print "Bright :" + str(bright_mean) + " Dark: " + str(dark_mean) +  "the contrast value is :" + str(bright_mean/dark_mean) #access table by col and row