예제 #1
0
	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()
예제 #2
0
def find_maxima_stack(imp, tolerance):
  stack = imp.getImageStack()
  stack_out = ImageStack(imp.width, imp.height)
  for i in range(1, imp.getNSlices() + 1):
    ip = stack.getProcessor(i)
    # findMaxima(ImageProcessor ip, double tolerance, double threshold, int outputType, boolean excludeOnEdges, boolean isEDM)
    ip_max = MaximumFinder().findMaxima(ip, tolerance, ImageProcessor.NO_THRESHOLD, MaximumFinder.IN_TOLERANCE, False, False)
    stack_out.addSlice(str(i), ip_max)
    #segip.invert()
  return ImagePlus("Maxima", stack_out)
def findCells(imp, rm, channel, noisetol, thresh):
    '''
	Function for finding cells as local maxima and creating an ROI showing them
	imp: ImagePlus
	rm: the current ROI manager
	channel, int: the channel being processed (used for ROI name)
	noisetol, thresh, ints: noise tolerance and pixel value threshold for findMaxima

	returns the count
	'''

    # set the channel
    imp.setC(channel)

    # find maxima
    ip = imp.getProcessor()
    mf = MaximumFinder()
    maxima = mf.findMaxima(ip, noisetol, thresh, MaximumFinder.SINGLE_POINTS,
                           False, False)

    findmaximashow = ImagePlus("Found Maxima", maxima)
    findmaximashow.show()  # an image of all the points
    maximaip = findmaximashow.getProcessor()
    maximahist = maximaip.getHistogram()
    cellCount = maximahist[255]

    if cellCount != 0:
        IJ.setRawThreshold(findmaximashow, 255, 255, "red")
        IJ.run(findmaximashow, "Create Selection", "")
        rm.addRoi(findmaximashow.getRoi()
                  )  # a selection consisting of all the points

    # close maxima image if present
    if findmaximashow:
        findmaximashow.close()

    return cellCount
def mask2D(ip, sigmaPx, k, method, minimum, doFillHoles, doWatershed):
    mask = ip.duplicate()
    sub = mask.duplicate()
    mask.blurGaussian(sigmaPx)
    if k > 0:
        sub.blurGaussian(k * sigmaPx)
        mask.copyBits(sub, 0, 0, Blitter.SUBTRACT)

    stats = mask.getStatistics()
    hist = mask.getStatistics().histogram
    thresh = AutoThresholder().getThreshold(method, hist)
    thresh = (thresh / float(255)) * (stats.max - stats.min) + stats.min

    mask.threshold(int(thresh))
    mask = mask.convertToByte(False)

    if doFillHoles:
        fillHoles(mask)

    if doWatershed:
        floatEdm = EDM().makeFloatEDM(mask, 0, False)
        maxIp = MaximumFinder().findMaxima(floatEdm, 0.5,
                                           ImageProcessor.NO_THRESHOLD,
                                           MaximumFinder.SEGMENTED, False,
                                           True)
        if (maxIp != None):
            mask.copyBits(maxIp, 0, 0, Blitter.AND)

    mask.dilate()
    mask.erode()

    mask.setThreshold(255, 255, ImageProcessor.NO_LUT_UPDATE)
    roi = ThresholdToSelection().convert(mask)
    ip.setRoi(roi)
    mean = ip.getStatistics().mean

    if mean < minimum:  #if the mask area intensity mean in the original image is less than the minimum required
        mask = ByteProcessor(ip.getWidth(), ip.getHeight())  #return empty mask

    return mask
		# clijx.show(sphereProjection, "sphereProjection");
		# break;
		
		clijx.resliceLeft(sphereProjection, sphereProjectionTransformed);
		clijx.maximumZProjection(sphereProjectionTransformed, sphereMaxProjection);

	# Spot detection
	if (formerTolerance != tolerance or formerThreshold != threshold or formerDoSpotDetection != doSpotDetection):
		formerTolerance = tolerance;
		formerThreshold = threshold;
		formerDoSpotDetection = doSpotDetection;
		stillValid = False;

	if (not stillValid):
		if (doSpotDetection):
			projectionImp = clijx.pull(sphereMaxProjection);
			binary = MaximumFinder().findMaxima(projectionImp.getProcessor(), tolerance, True, threshold, MaximumFinder.SINGLE_POINTS, False, False);
			projectionImp.setProcessor(binary); 
			#projectionImp.show();
			
			if (spots is not None):
				spots.close();
			spots = clijx.push(projectionImp);
			if (circles is None):
				circles = clijx.create(spots);
			if (blobs is None):
				blobs = clijx.create(spots);
	
			clijx.dilateBox(spots, blobs);
			clijx.dilateSphere(blobs, spots);
			clijx.subtract(spots, blobs, circles);		
예제 #6
0
def cellSegmentation(srcDir, dstDir, currentDir, filename, keepDirectories):
  print "Processing:"  
  # Opening the image
  print "Open image file", filename
  imp = IJ.openImage(os.path.join(currentDir, dstDir))
  # Put your processing commands here!
  localinput=srcDir.replace("/", "\\")
  saveDir = localinput.replace(srcDir, dstDir)
  string="."
  dotIndex=filename.find(string)
  localfile= filename[0:dotIndex]
  print(localfile)
  IJ.run("New... ", "name="+f+" type=Table")
  print(f,"\\Headings:Cell\tarea\tCirc\tAR\tRoundness\tMaximum")
  IJ.run("Bio-Formats", "open=[" + localinput + os.path.sep + filename +"] autoscale color_mode=Default rois_import=[ROI manager] view=Hyperstack stack_order=XYCZT")
  IJ.open()
  idd= WM.getIDList();
  imageID= idd[0];
  IJ.run("Clear Results")
  WM.getImage(imageID)
  IJ.run("Duplicate...", "duplicate channels="+str(x)+"") #Nucleus channel #took away x
  IJ.run("Z Project...", "projection=[Standard Deviation]");#picture for frame detection
  IJ.run("8-bit");
  IJ.run("Duplicate...", "title=IMAGE");#frame
  IJ.run("Duplicate...", "title=SUBTRACT");#Background subtraction mask (for frame and watershed)
  imp=IJ.getImage()
  pixelWidth=imp.getWidth()
  pixelWidth=pixelWidth/1647.89
  pixelHeight= imp.getHeight()
#create subtraction mask, applying constraining maximum (step I)
  IJ.selectWindow("SUBTRACT")
  nResults=imp.getStatistics()
  row = nResults
  rt_exist = WM.getWindow("Results")
  if rt_exist==None:
    rt= ResultsTable()
  else:
    rt = rt_exist.getTextPanel().getOrCreateResultsTable()
  rt.setValue("Max ", 0, row.max) #text file
  rt.show("Results")
  u=math.floor(row.mean*3)
  IJ.run("Max...","value="+str(u)) #constraining maximum of 3-fold mean to reduce effect of extreme values during subtraction
		#gaussian blurring (step II)
  IJ.run("Gaussian Blur...", "sigma=100 scaled") #blurring for subtraction mask

  IJ.selectWindow("IMAGE")
  pxrollrad = cellradius/pixelWidth; #rolling ball radius in pixels needed (= predefined cell radius[µm]/pixelsize[µm/px])
  IJ.run("Subtract Background...", "rolling="+str(pxrollrad)+"")
  IJ.run("Gaussian Blur...", "sigma=2 scaled") #reduces punctate character of grayscale image '
  IM=IJ.selectWindow("IMAGE")
  SUB=IJ.selectWindow("SUBTRACT")
  ic().run("SUBTRACT", IM, SUB) #just subtracts two images
  IJ.selectWindow("IMAGE") #see how to call
  IJ.run("Duplicate...", "title=AND")#watershed
  IJ.run("Duplicate...", "title=CHECK")#for checking if maxima exist within selection later
  
#Apply threshold to get binary image of cell borders (step IV)
  IJ.selectWindow("IMAGE")
  imp = IJ.getImage()  # the current image
  imp.getProcessor().setThreshold(1, 255, ImageProcessor.NO_LUT_UPDATE)
  IJ.run("Subtract Background...","...")
  IJ.run("Convert to Mask", "method=Default background=Dark only black")
  IJ.run("Fill Holes")

#Create watershed line image (step V)
  IJ.selectWindow("AND")
  IJ.run("Gaussian Blur...", "sigma=2 scaled")
  imp=IJ.getImage()
  pixelWidth=imp.getWidth()
  pixelWidth=pixelWidth/1647.89
  pixelHeight= imp.getHeight()
  # Saving the image
  nResults=imp.getStatistics()
  row = nResults
  rt.setValue("Max ", 1, row.max) #text file
  nBins = 256
  Hist = HistogramWindow("Histogram",imp,nBins)
  Table = Hist.getResultsTable()
  Counts = Table.getColumn(1)
  #mean gray value of pixels belonging to cells needed (i.e. mean of ONLY non-zero pixel)
  Sum = 0 #all counts
  CV = 0 #weighed counts (= counts * intensity)
  for i in range(0, len(Counts)): #starting with 1 instead of 0. -> 0 intensity values are not considered.
    Sum += Counts[i]
    CV += Counts[i]*i
  m = (CV/Sum)
  m=math.floor(m)
  l = math.floor(2*m) #Maxima need to be at least twice the intensity of cellular mean intensity
  IJ.run("Find Maxima...", "noise="+str(l)+" output=[Segmented Particles] exclude") #watershedding

#Combine watershed lines and cell frame (step VI) 
  IJ.selectWindow("IMAGE")
  imp=IJ.getImage()
  imp.getProcessor().setThreshold(1, 255, ImageProcessor.NO_LUT_UPDATE)
  IJ.run(imp, "Watershed", "") #useful
  imp = IJ.getImage()
  ip = imp.getProcessor()
  segip = MaximumFinder().findMaxima( ip, 1, ImageProcessor.NO_THRESHOLD, MaximumFinder.SEGMENTED , False, False)
  segip.invert()
  segimp = ImagePlus("seg", segip)
  segimp.show()
  mergeimp = RGBStackMerge.mergeChannels(array([segimp, None, None, imp, None, None, None], ImagePlus), True)
  mergeimp.show()
  pa_exist = WM.getWindow("Results for PA")   
  if pa_exist==None:
    pa_rt= ResultsTable()   
  else:
    pa_rt = pa_exist.getTextPanel().getOrCreateResultsTable()     
  ParticleAnalyzer.setResultsTable(pa_rt)    
  IJ.run("Set Measurements...", "area mean perimeter shape decimal=3")  
  IJ.run("Analyze Particles...", "size=" + str(cellradius) + "-Infinity circularity=0.1-1.00 add"); #Cell bodies detected 
  pa_rt.show("Results for PA ")
  save_all(srcDir, dstDir, filename, localfile, keepDirectories, imageID)
예제 #7
0
    One = Scalar(1.0)
    CorrMapInvCV = subtract(One, CorrMapCV).asMat()
    #CorrMapInv = MatToImProc(CorrMapInvCV)
    #CorrMapInv = ImagePlus("Inverted", CorrMapInv)
    #CorrMapInv.show()

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

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

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

## For both cases (Multi-Min/Max-detection) detect maxima on the thresholded map
excludeOnEdge = False  # otherwise miss quite a lot of them
tolerance = 0
Polygon = MaximumFinder().getMaxima(CorrMapThresh, tolerance, excludeOnEdge)
roi = PointRoi(Polygon)
CorrMapThreshImp.setRoi(roi)
from java.awt import *
import itertools
from ij.gui import Roi
from ij.gui import PointRoi, OvalRoi
from java.lang import Boolean
import time
import itertools
import glob
import os
from ij.gui import WaitForUserDialog

from ij.plugin.filter import MaximumFinder
from ij.process import ImageProcessor
from ij import IJ, ImagePlus, ImageStack
from ij.gui import PointRoi
mf = MaximumFinder()
from ij.measure import Measurements
# Indicate channel which should be used for Thresholding

# Save the results automatically as  CSV file ?
automatic_save_results = True


do_dog_C1 = False
do_dog_C2 = False


savepath = "d://test3//SCR"


#path for CSV fave
예제 #9
0
	def __fmaxfinder(self) :
		#stack = self.__impRes.getStack()
		self.__impD.killRoi()
		self.__impF.killRoi()
		stack = self.__impF.getStack()
		n_slices = stack.getSize()
		#newstack=ImageStack(self.__impRes.getWidth(), self.__impRes.getHeight())
		newstack=ImageStack(self.__impF.getWidth(), self.__impF.getHeight())
		noise = self.__display3.text
		for index in range(1,n_slices+1):
			IJ.selectWindow(self.__impF.getTitle())
			self.__impF.setSlice(index)
			ip = self.__impF.getProcessor()
			mf=MaximumFinder()
			ipmax = mf.findMaxima(ip, int(noise), 0, 0, False, False)
			newstack.addSlice("", ipmax)
			

		newimage=ImagePlus("max points"+self.__name, newstack)
		newimage.show()
		newimage.updateAndDraw()
		
		listip = []
		maxh=self.__impRes.getHeight()

		for roi in self.__cellsrois : 
			straightener = Straightener()
			newimage.setSlice(roi[1])
			newimage.setRoi(roi[0])
			#listip.append(straightener.straighten(newimage, roi[0], int(self.__widthl)))
			listip.append(straightener.straighten(newimage, roi[0], maxh))
		
		ipw=[ ip.getWidth() for ip in listip ]
		iph=[ ip.getHeight() for ip in listip ]
		maxw=max(ipw)
		maxh=max(iph)
		
		if self.__enlarge : resizelist = [ ip.resize(maxw, maxh, True) for ip in listip ]
		
		elif  self.__alignC : 
			resizelist = []
			for ip in listip :
				tempip = ByteProcessor(maxw, maxh)
				tempip.copyBits(ip, 0, 0, Blitter.COPY)
				resizelist.append(tempip)

		else :
			resizelist = []
			for ip in listip :
				tempip = ByteProcessor(maxw, maxh)
				tempip.copyBits(ip, 0, 0, Blitter.COPY)
				resizelist.append(tempip)
				
		ims = ImageStack(maxw, maxh) 	
		
		#for ip in resizelist : ims.addSlice("", ip)
		for i in range(len(resizelist)) : 
			ims.addSlice(self.__labels[i], resizelist[i])
		
		self.__impMax = ImagePlus(self.__name+"-max", ims)
		self.__impMax.show()
		stack = self.__impMax.getStack() # get the stack within the ImagePlus
		n_slices = stack.getSize()
		
		for index in range(1, n_slices+1):
			self.__impMax.killRoi()	
			self.__impMax.setSlice(index)
			roi = self.__listrois[index-1]
			
			if self.__sens[index-1]<0 : 
				self.__impMax.setRoi(roi)
				ip1 = self.__impMax.getProcessor()
				ip1.flipHorizontal()
				self.__impMax.killRoi()
				self.__impMax.updateAndDraw()

			ip = self.__impMax.getProcessor()
			for i in range(ip.getWidth()*ip.getHeight()) :
				if ip.getf(i) > 0 : ip.setf(i, 255)
				#else : ip.setf(i, 0)

		IJ.run(self.__impMax, "8-bit", "")
		IJ.run(self.__impMax, "Options...", "iterations=2 count=1 black edm=Overwrite do=Close stack")
		IJ.run(self.__impMax, "Ultimate Points", "stack")
		
		self.__impMax.updateAndDraw()
예제 #10
0
def watershed(ip):
    TOL = 0.5
    floatEdm = EDM().makeFloatEDM(ip, 0, False)
    maxIp = MaximumFinder().findMaxima(floatEdm, TOL, ImageProcessor.NO_THRESHOLD, MaximumFinder.SEGMENTED, False, True)
    if (maxIp != None):
        ip.copyBits(maxIp, 0, 0, Blitter.AND)
    rm = RoiManager.getInstance()
    if not rm:
        rm = RoiManager()
    if new:
        rm.runCommand("Reset")
    return rm


# ---- SETUP
imp = IJ.openImage("http://imagej.nih.gov/ij/images/m51.zip"
                   )  # galaxy, 16 bit dark background
imp.show()
rm = get_roi_manager(new=True)

ip = imp.getProcessor()
mf = MaximumFinder()
THRESH = 700.0

# ---- METHOD 1: IJ.RUN("Find Maxima")
# Menu-based find maxima command -- does not support threshold

IJ.run(imp, "Find Maxima...", "noise=100 output=[Point Selection]")
rm.addRoi(imp.getRoi())
rm.rename(0, "Maxima without threshold")
rm.select(0)
IJ.run(imp, "Measure", "")
rt = ResultsTable.getResultsTable()
CountMethod1 = rt.getCounter()
CountMethod1 = float(CountMethod1)
rt.reset()  # supposed to reset the results table
postReset = rt.getCounter()
예제 #12
0
from ij.io import DirectoryChooser
from ij.io import OpenDialog
from ij.measure import ResultsTable
from ij.measure import Measurements
from ij.process import ImageProcessor
from ij.process import ImageConverter
from ij.plugin.frame import RoiManager
from ij.plugin.filter import ParticleAnalyzer
from ij.gui import GenericDialog
from ij.gui import WaitForUserDialog
from ij.plugin.filter import MaximumFinder
from ij.plugin.filter import ThresholdToSelection
from ij.WindowManager import getImage
from ij.WindowManager import setTempCurrentImage

MF = MaximumFinder()

# A few default options

areaFractionThreshold = [85, 85, 85, 85, 85]  #you can change these
blur = 2
maxima = 20

lowerBounds = [205, 180, 205, 205, 205]

# display Images checkbox

displayImages = False

gd = GenericDialog("Set Threshold Mode")
gd.addChoice("Would you like to enable thresholding mode?",
예제 #13
0
ring_rois = []
unzip_axis = []
roi_stack = IJ.createImage("rois", egfp_imp.getWidth(), egfp_imp.getHeight(),
                           egfp_imp.getNSlices(), 16)
#roi_stack.show();

for zidx in range(cl_imp.getNSlices()):
    #for zidx in range(200,350):
    #for zidx in range(200,202):
    if ((zidx + 1) % 100) == 0:
        print("Z = " + str(zidx + 1))
    projected_im_row = []
    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))
     options.append( output_type_str )
     if exclude_edge_maxima:
         options.append( 'exclude' )
     if light_background:
         options.append( 'light' )
     # Run the command.
     IJ.run( input_image_plus_copy, "Find Maxima...", "%s" % " ".join( options ) )
     results_table = analyzer.getResultsTable()
     results_table.saveAs( tmp_output_path )
 else:
     # Find the maxima of an image (does not find minima).
     # LIMITATIONS: With output_type=Segmented_Particles
     # (watershed segmentation), some segmentation lines
     # may be improperly placed if local maxima are suppressed
     # by the tolerance.
     mf = MaximumFinder()
     if output_type == 'Single_Points':
         output_type_param = mf.SINGLE_POINTS
     elif output_type == 'Maxima_Within_Tolerance':
         output_type_param = mf.IN_TOLERANCE
     elif output_type == 'Segmented_Particles':
         output_type_param = mf.SEGMENTED
     elif output_type == 'List':
         output_type_param = mf.LIST
     elif output_type == 'Count':
         output_type_param = mf.COUNT
     # Get a new byteProcessor with a normal (uninverted) LUT where
     # the marked points are set to 255 (Background 0). Pixels outside
     # of the roi of the input image_processor_copy are not set. No
     # output image is created for output types POINT_SELECTION, LIST
     # and COUNT.  In these cases findMaxima returns null.
예제 #15
0
     if exclude_edge_maxima:
         options.append('exclude')
     if light_background:
         options.append('light')
     # Run the command.
     IJ.run(input_image_plus_copy, "Find Maxima...",
            "%s" % " ".join(options))
     results_table = analyzer.getResultsTable()
     results_table.saveAs(tmp_output_path)
 else:
     # Find the maxima of an image (does not find minima).
     # LIMITATIONS: With output_type=Segmented_Particles
     # (watershed segmentation), some segmentation lines
     # may be improperly placed if local maxima are suppressed
     # by the tolerance.
     mf = MaximumFinder()
     if output_type == 'Single_Points':
         output_type_param = mf.SINGLE_POINTS
     elif output_type == 'Maxima_Within_Tolerance':
         output_type_param = mf.IN_TOLERANCE
     elif output_type == 'Segmented_Particles':
         output_type_param = mf.SEGMENTED
     elif output_type == 'List':
         output_type_param = mf.LIST
     elif output_type == 'Count':
         output_type_param = mf.COUNT
     # Get a new byteProcessor with a normal (uninverted) LUT where
     # the marked points are set to 255 (Background 0). Pixels outside
     # of the roi of the input image_processor_copy are not set. No
     # output image is created for output types POINT_SELECTION, LIST
     # and COUNT.  In these cases findMaxima returns null.
def get_centroids(imp, tolerance):
    """ Returns maxima using IJ1 """
    mf = MaximumFinder()
    maxima = mf.getMaxima(imp.getProcessor(), tolerance, True)
    return maxima.xpoints, maxima.ypoints, maxima.npoints
예제 #17
0
# testMaximumFinder.py
# translated to Jython by J. R. Minter based upon a JavaScript example
# by Wayne Rasband.
# It uses the MaximumFinder.getMaxima() method, which returns the list of x,y
# coordinates as a Polygon.
#  Modifications
#   Date      Who  Ver                       What
# ----------  --- ------  -------------------------------------------------
# 2015-01-23  JRM 0.1.00  Initial translation
# 
from org.python.core import codecs
codecs.setDefaultEncoding('utf-8')

from ij import IJ
from ij.plugin.filter import MaximumFinder

tolerance = 50
excludeOnEdges = False
img = IJ.openImage("http://imagej.nih.gov/ij/images/blobs.gif")
ip = img.getProcessor()
mf = MaximumFinder()
maxima = mf.getMaxima(ip, tolerance, excludeOnEdges)
print("count = %d" % maxima.npoints)
def FindMinMax(CorrMapCV, Unique=True, MinMax="Max", Score_Threshold=0.5, Tolerance=0):
	'''
	Detect Minima(s) or Maxima(s) in the correlation map
	The function uses for that the MinMaxLoc from opencv for unique detection 
	or the MaximumFinder from ImageJ for multi-detection (in this case, for min detection the correlation map is inverted)
	
	- Unique			: True if we look for one global min/max, False if we want local ones
	- MinMax 			: "Min" if we look for Minima, "Max" if we look for maxima
	- Score_Threshold 	: in range [0;1] (correlation maps are normalised)
	- Tolerance 		: Parameters for flood-fill. Not used here so should be set to 0 
	
	Returns List of Min/Max : [(X, Y, Coefficient), ... ]
	'''
	#### Detect min/maxima of correlation map ####
	Extrema = [] 
	
	## if 1 hit expected
	if Unique: # Look for THE global min/max
		minVal = DoublePointer(1) 
		maxVal = DoublePointer(1) 
		minLoc = Point() 
		maxLoc = Point() 
		minMaxLoc(CorrMapCV, minVal, maxVal, minLoc, maxLoc, Mat())
		
		if MinMax=="Min": # For method based on difference we look at the min value 
			X = minLoc.x() 
			Y = minLoc.y()
			Coeff = minVal.get() 
	 
		elif MinMax=="Max": 
			X = maxLoc.x() 
			Y = maxLoc.y()
			Coeff = maxVal.get()
		
		# Append to the output list
		Extrema.append( (X, Y, Coeff) )
		
		
	
	## if more hit expected
	else: # expect more than 1 template/image. Do a multi minima/maxima detection
		
		## OLD CODE LEFT BUT DONT DO IT, NOT GOOD PREACTICE !! Normalise the correlation map to 0-1 (easier to apply the threshold)
		## Rather use normalised method only for the computation of the correlation map (by default normalised method are 0-1 bound)
		# The normalised method are already normalised to 0-1 but it is more work to take it into account in this function 
		# WARNING : this normalisation normalise regarding to the maxima of the given correlation map
		# Not good because it means the thresholding is define relative to a correlation map : a score of 1 might not correspond to a correlation of 1
		# But only means that the pixel was the maximum of this particular correlation map 
		
		#CorrMapNormCV = Mat()
		#normalize(CorrMapCV, CorrMapNormCV, 0, 1, NORM_MINMAX, CV_32FC1, None)

		# Visualisation for debugging
		#CorrMapNorm = MatToImProc(CorrMapNormCV)
		#CorrMapNorm = ImagePlus("Normalised", CorrMapNorm)
		#CorrMapNorm.show()

		
		
		### Maxima/Minima detection on the correlation map
		
		## Difference-based method : we look for min value. For that we detect maxima on an inverted correlation map
		if MinMax=="Min": 
			
			# Invert the correlation map : min becomes maxima
			One = Scalar(1.0)
			CorrMapInvCV = subtract(One, CorrMapCV).asMat()		
			#CorrMapInv = MatToImProc(CorrMapInvCV)
			#CorrMapInv = ImagePlus("Inverted", CorrMapInv)
			#CorrMapInv.show()
			
			
			# Apply a "TO ZERO" threshold on the correlation map : to compensate the fact that maxima finder does not have a threshold argument
			# TO ZERO : below the threshold set to 0, above left untouched
			# NB : 1-score_threshold since we have inverted the image : we want to look for minima of value <x so we have to look for maxima of value>1-x in the inverted image
			CorrMapThreshCV = Mat()
			threshold(CorrMapInvCV, CorrMapThreshCV, 1-Score_Threshold, 0, CV_THRESH_TOZERO)
			CorrMapThresh = MatToImProc(CorrMapThreshCV) # Keep this conversion, not only for visualisation
			#CorrMapThreshImp = ImagePlus("Thresholded", CorrMapThresh)
			#CorrMapThreshImp.show()
			

		
		## Correlation-based method : we look for maxima
		elif MinMax=="Max": 
			# Apply a "TO ZERO" threshold on the correlation map : to compensate the fact that maxima finder does not have a threshold argument
			# TO ZERO : below the threshold set to 0, above left untouched
			# NB : 1-score_threshold since we have inverted the image : we want to look for minima of value <x so we have to look for maxima of value>1-x in the inverted image
			CorrMapThreshCV = Mat()
			threshold(CorrMapCV, CorrMapThreshCV, Score_Threshold, 0, CV_THRESH_TOZERO)
			CorrMapThresh = MatToImProc(CorrMapThreshCV) # Keep this conversion, not only for visualisation
			#CorrMapThreshImp = ImagePlus("Thresholded", CorrMapThresh)
			#CorrMapThreshImp.show()
			
		
		
		## For both cases (Multi-Min/Max-detection) detect maxima on the thresholded map
		# Detect local maxima
		excludeOnEdge = False # otherwise miss quite a lot of them
		Polygon = MaximumFinder().getMaxima(CorrMapThresh, Tolerance, excludeOnEdge)
		
		# Maxima as list of points
		#roi = PointRoi(Polygon)
		
		# Generate Hit from max coordinates
		#print Polygon.npoints," maxima detected in this score map"
		if Polygon.npoints!=0: # Check that there are some points indeed. Otherwise Polygon.xpoints and ypoints are anyway initialised with [0,0,0,0] even if Npoints=0 !
			
			for i in range(Polygon.npoints): # dont directly loop on xpoints and ypoint since initialised with [0,0,0,0] ie less than 4 points we get some 0,0 coordinates
			
				# Get point coordinates
				X, Y = Polygon.xpoints[i], Polygon.ypoints[i]

				# Get Coeff
				Coeff = CorrMapThresh.getPixel(X, Y)
				Coeff = Float.intBitsToFloat(Coeff) # require java.lang.Float
				
				# Revert the score again if we were detecting minima initially (since found as maxima of a reverted correlation map)
				if MinMax=="Min":
					Coeff = 1-Coeff
				
				# Wrap into corresponding hit
				Extrema.append( (X, Y, Coeff) )
	
	return Extrema
예제 #19
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")