def measureTumor(original, locations): '''Returns the area from the original image with the highest kurtosis which generally corresponds to the most in focus image. Also saves an image corresponding to a mask of the measurement.''' # Prevent ROI manager from appearing roiM = RoiManager(True) ParticleAnalyzer.setRoiManager(roiM) # Locate particles above a minimum size and with a desired circularity IJ.run(locations, "Analyze Particles...", "size=" + str(minimumCancerArea) +"-" + str(maxCancerArea) +" circularity=" + str(circularityCutoff) + "-1.00 show=Nothing exclude add stack"); # Choose ROI with the highest kurtosis maxKurtosis = None area = None selectedROI = None for roi in roiM.getRoisAsArray(): original.setRoi(roi) stats = original.getStatistics(Measurements.KURTOSIS, Measurements.AREA) currentKurtosis = stats.kurtosis if currentKurtosis > maxKurtosis: maxKurtosis = stats.kurtosis area = stats.area selectedROI = roi original.killRoi() # Remove the remaining ROI roiM.runCommand("Reset") return (area, selectedROI)
def particleAnalysis(slicenum, sliceimp, resrt): options = PA.SHOW_NONE rt = ResultsTable() p = PA(options, PA.AREA + PA.CENTROID, rt, MINSIZE, MAXSIZE) p.analyze(sliceimp) centrosomecounts = rt.getCounter() print "-- Region", str(slicenum), "--" curCount = resrt.getCounter() resrt.setValue("cellID", curCount, slicenum) resrt.setValue("counts", curCount, centrosomecounts) if centrosomecounts == 0: print " .. no centrosome" elif centrosomecounts == 1: print " .. Only one centrosome" # if rt.getValue("Area", 0) == 1.0: # print " .. Only one centrosome" # else: # print " .. one centrosome but Area 1 < : maybe combined" elif centrosomecounts == 2: print " .. two centrosomes" resrt.setValue("c1x", curCount, rt.getValue("X", 0)) resrt.setValue("c1y", curCount, rt.getValue("Y", 0)) resrt.setValue("c2x", curCount, rt.getValue("X", 1)) resrt.setValue("c2y", curCount, rt.getValue("Y", 1)) else: print " .. ", str(centrosomecounts),"centrosomes detected"
def anaParticles(imp, minSize, maxSize, minCirc, bHeadless=True): """anaParticles(imp, minSize, maxSize, minCirc, bHeadless=True) Analyze particles using a watershed separation. If headless=True, we cannot redirect the intensity measurement to the original immage becuae it is never displayed. If we display the original, we can and get the mean gray level. We may then compute the particle contrast from the measured Izero value for the image. No ability here to draw outlines on the original.""" strName = imp.getShortTitle() imp.setTitle("original") ret = imp.duplicate() IJ.run(ret, "Enhance Contrast", "saturated=0.35") IJ.run(ret, "8-bit", "") IJ.run(ret, "Threshold", "method=Default white") IJ.run(ret, "Watershed", "") rt = ResultsTable() # strSetMeas = "area mean modal min center perimeter bounding fit shape feret's redirect='original' decimal=3" # N.B. redirect will not work without a displayed image, so we cannot use a gray level image if bHeadless == True: strSetMeas = "area mean modal min center perimeter bounding fit shape feret's decimal=3" else: imp.show() strSetMeas = "area mean modal min center perimeter bounding fit shape feret's redirect='original' decimal=3" IJ.run("Set Measurements...", strSetMeas) # note this doies not get passed directly to ParticleAnalyzer, so # I did this, saved everything and looked for the measurement value in ~/Library/Preferences/IJ_Prefs.txt # measurements=27355 # meas = Measurements.AREA + Measurements.CIRCULARITY + Measurements.PERIMETER + Measurements.SHAPE_DESCRIPTORS # didn't work reliably meas = 27355 pa = ParticleAnalyzer(0, meas, rt, minSize, maxSize, minCirc, 1.0); pa.analyze(ret); rt.createTableFromImage(ret.getProcessor()) return [ret, rt]
def resetpressed(event): self.__ranges.clear() self.__image=IJ.getImage() rm = RoiManager.getInstance() if (rm==None): rm = RoiManager() rm.runCommand("reset") self.__image.killRoi() IJ.setAutoThreshold(self.__image, "MaxEntropy") rt=ResultsTable() pa=ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER+ParticleAnalyzer.CLEAR_WORKSHEET , Measurements.AREA+Measurements.ELLIPSE+Measurements.MEAN, rt, 0.00, 10000.00, 0.00, 1.00) pa.analyze(self.__image) self.__roisArray=[] self.__roisArray=rm.getRoisAsArray() #rm.runCommand("Show All") #rm.runCommand("Select All") #rm.runCommand("Set Color", "blue") IJ.resetThreshold(self.__image) keys=self.__slidersDict.keys() for k in keys: if k.endswith("min"): self.__slidersDict[k].setValue(0) self.__slidersDict[k].repaint() else: self.__slidersDict[k].setValue(self.__slidersDict[k].getMaximum()) self.__slidersDict[k].repaint()
def particleRemover(image, minArea): '''Send in a thresholded image, remove the small spots''' numSlices = image.getImageStackSize() particleRoiM = RoiManager(True) ParticleAnalyzer.setRoiManager(particleRoiM) IJ.run(image, "Analyze Particles...", "size=0-" + str(minArea) + " circularity=0.00-1.00 include show=Nothing add stack"); # Set the fill color to black before filling IJ.setForegroundColor(0, 0, 0); particleRoiM.runCommand("Fill"); particleRoiM.runCommand("Reset");
def measure(self): imp = IJ.openImage(self.filename) IJ.log("Input file: %s" % self.filename) ImageConverter(imp).convertToGray8() res = Auto_Threshold().exec(imp, self.myMethod, self.noWhite, self.noBlack, self.doIwhite, self.doIset, self.doIlog, self.doIstackHistogram) rt = ResultsTable() rt.showRowNumbers(False) pa = PA(self.options, PA.AREA + PA.PERIMETER + PA.CIRCULARITY, rt, self.MINSIZE, self.MAXSIZE) pa.analyze(imp) self.result = self.rtToResult(rt) self.mask = imp
def test(): newImg = ImagePlus("GrayScaled",imp) newip = newImg.getProcessor() hist = newip.getHistogram() lowTH = Auto_Threshold.IsoData(hist) newip.setThreshold(lowTH, max(hist),ImageProcessor.BLACK_AND_WHITE_LUT) rt = ResultsTable() pa = ParticleAnalyzer(ParticleAnalyzer.SHOW_RESULTS | ParticleAnalyzer.SHOW_OVERLAY_OUTLINES, Measurements.AREA |Measurements.MEAN |\ Measurements.MEDIAN | Measurements.STD_DEV | Measurements.MIN_MAX | Measurements.RECT, rt,50, 200000, 0.5, 1 ) pa.setResultsTable(rt) pa.analyze(newImg) rt.show("Results")
def segmentNuc(impc2): impdup = Duplicator().run(impc2) IJ.run(impdup, "8-bit", "") IJ.run(impdup, "Gaussian Blur...", "sigma=1.5 stack") # AutoThresholder().getThreshold(AutoThresholder.Method.valuOf('Otsu'), int[] histogram) IJ.setAutoThreshold(impdup, "Otsu dark") IJ.run(impdup, "Convert to Mask", "stack") #IJ.setAutoThreshold(impdup, "Otsu dark") #opt = PA.SHOW_MASKS + PA.SHOW_RESULTS + PA.EXCLUDE_EDGE_PARTICLES + PA.INCLUDE_HOLES # option for stack missing opt = PA.SHOW_MASKS + PA.EXCLUDE_EDGE_PARTICLES + PA.INCLUDE_HOLES # option for stack missing ##area mean centroid bounding integrated stack redirect=None decimal=4 meas = Meas.AREA + Meas.MEAN + Meas.CENTROID + Meas.RECT + Meas.INTEGRATED_DENSITY + Meas.STACK_POSITION rt = ResultsTable().getResultsTable() pa = PA(opt, meas, rt, 10.0, 300000.0, 0, 1.0) PA.processStack = True pa.setHideOutputImage(True) ##run("Analyze Particles...", "size=800-Infinity circularity=0.00-1.00 pixel show=Masks display exclude include stack"); outstack = ImageStack(impdup.getWidth(), impdup.getHeight()) for i in range(1,impdup.getStackSize()+1): impdup.setSlice(i) pa.analyze(impdup) impbin = pa.getOutputImage() outstack.addSlice(impbin.getProcessor()) impbin = ImagePlus("out", outstack) IJ.run(impbin, "Invert LUT", "") #IJ.run(impbin, "Fill Holes", "stack") return impbin, rt
def getParticleCenters(imp): # Create a table to store the results rt = ResultsTable() paOpts = PA.SHOW_OUTLINES \ + PA.INCLUDE_HOLES \ + PA.EXCLUDE_EDGE_PARTICLES measurements = PA.CENTROID + PA.CENTER_OF_MASS MINSIZE = 1000 MAXSIZE = Double.POSITIVE_INFINITY pa = PA(paOpts,measurements, rt, MINSIZE, MAXSIZE) pa.setHideOutputImage(True) if not pa.analyze(imp): print "There was a problem in analyzing", imp # The measured centroids are listed in the first column of the results table, as a float array: centroids_x = rt.getColumn(rt.X_CENTROID) centroids_y = rt.getColumn(rt.Y_CENTROID) coms_x = rt.getColumn(rt.X_CENTER_OF_MASS) coms_y = rt.getColumn(rt.Y_CENTER_OF_MASS) return (centroids_x,centroids_y, coms_x, coms_y)
def anaParticles(imp, minSize, maxSize, minCirc): strName = imp.getShortTitle() imp.setTitle("original") ret = imp.duplicate() IJ.run(ret, "Enhance Contrast", "saturated=0.35") IJ.run(ret, "8-bit", "") IJ.run(ret, "Threshold", "method=Default white") IJ.run(ret, "Watershed", "") rt = ResultsTable() # strSetMeas = "area mean modal min center perimeter bounding fit shape feret's redirect='original' decimal=3" # N.B. redirect will not work without a displayed image, so we cannot use a gray level image strSetMeas = "area mean modal min center perimeter bounding fit shape feret's decimal=3" IJ.run("Set Measurements...", strSetMeas) # note this doies not get passed directly to ParticleAnalyzer, so # I did this, saved everything and looked for the measurement value in ~/Library/Preferences/IJ_Prefs.txt # measurements=27355 # meas = Measurements.AREA + Measurements.CIRCULARITY + Measurements.PERIMETER + Measurements.SHAPE_DESCRIPTORS # didn't work reliably meas = 27355 pa = ParticleAnalyzer(0, meas, rt, minSize, maxSize, minCirc, 1.0); pa.analyze(ret); rt.createTableFromImage(ret.getProcessor()) return [ret, rt]
def countParticles(imp, roim, minSize, maxSize, minCircularity, maxCircularity): # Create a table to store the results table = ResultsTable() # Create the particle analyzer pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA|Measurements.MEAN, table, minSize, maxSize, minCircularity, maxCircularity) #pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA|Measurements.MEAN, table, 10, Double.POSITIVE_INFINITY, 0.5, 1.0) #pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA|Measurements.MEAN, table, 5, 6, 0.5, 1.0) pa.setRoiManager(roim) pa.setHideOutputImage(True) if pa.analyze(imp): print "All ok" else: print "There was a problem in analyzing", blobs areas = table.getColumn(0) intensities = table.getColumn(1) if ( (areas!=None) and (intensities!=None)): for area, intensity in zip(areas,intensities): print str(area)+": "+str(intensity)
def analyzeParticles(imp, minsize, maxsize, mincirc, maxcirc, #filename='Test.czi', addROIManager=False, #headless=False, exclude=True): if GraphicsEnvironment.isHeadless(): print('Headless Mode detected. Do not use ROI Manager.') addROIManager = False if addROIManager: # get the ROI manager instance rm = RoiManager.getInstance() if rm is None: rm = RoiManager() rm.runCommand("Associate", "true") if not exclude: options = PA.SHOW_ROI_MASKS \ + PA.SHOW_RESULTS \ + PA.DISPLAY_SUMMARY \ + PA.ADD_TO_MANAGER \ + PA.ADD_TO_OVERLAY \ if exclude: options = PA.SHOW_ROI_MASKS \ + PA.SHOW_RESULTS \ + PA.DISPLAY_SUMMARY \ + PA.ADD_TO_MANAGER \ + PA.ADD_TO_OVERLAY \ + PA.EXCLUDE_EDGE_PARTICLES if not addROIManager: if not exclude: options = PA.SHOW_ROI_MASKS \ + PA.SHOW_RESULTS \ + PA.DISPLAY_SUMMARY \ + PA.ADD_TO_OVERLAY \ if exclude: options = PA.SHOW_ROI_MASKS \ + PA.SHOW_RESULTS \ + PA.DISPLAY_SUMMARY \ + PA.ADD_TO_OVERLAY \ + PA.EXCLUDE_EDGE_PARTICLES measurements = PA.STACK_POSITION \ + PA.LABELS \ + PA.AREA \ + PA.RECT \ + PA.PERIMETER \ + PA.SLICE \ + PA.SHAPE_DESCRIPTORS \ + PA.CENTER_OF_MASS \ + PA.CENTROID results = ResultsTable() p = PA(options, measurements, results, minsize, maxsize, mincirc, maxcirc) p.setHideOutputImage(True) particlestack = ImageStack(imp.getWidth(), imp.getHeight()) for i in range(imp.getStackSize()): imp.setSliceWithoutUpdate(i + 1) ip = imp.getProcessor() # convert to a mask for the particle analyzer ip.invert() # do the particle analysis p.analyze(imp, ip) mmap = p.getOutputImage() # add the slide to the full stack particlestack.addSlice(mmap.getProcessor()) return particlestack, results
# Path to the binary image, to be plotted with area. # binimgpath = '/Users/miura/Dropbox/people/Giogia_Stefano/toJoe/mask10frames.tif' binimgpath = "/Users/miura/Dropbox/people/Giogia_Stefano/toJoe/mask20framesOrg.tif" # binimgpath = '/Users/miura/Dropbox/people/Giogia_Stefano/toJoe/mask_z4_furrowSeg1.0.6_threshOffest5e-04_closingSize3_200f.tif' imp = IJ.openImage(binimgpath) # paOpt = PA.CLEAR_WORKSHEET +\ paOpt = PA.SHOW_OUTLINES + PA.EXCLUDE_EDGE_PARTICLES # +\ # PA.INCLUDE_HOLES #+ \ # PA.SHOW_RESULTS measOpt = PA.AREA + PA.CENTROID + PA.SLICE # + PA.SHAPE_DESCRIPTORS + PA.INTEGRATED_DENSITY rt = ResultsTable() MINSIZE = 2 MAXSIZE = 10000 pa = PA(paOpt, measOpt, rt, MINSIZE, MAXSIZE) pa.setHideOutputImage(True) # pa.processStack = True for i in range(imp.getStackSize()): imp.setSlice(i + 1) pa.analyze(imp) # pa.getOutputImage().show() rt.show("cells") # rt = ResultsTable.open2(path) dotlinker = DotLinker(loadmethod, rt) # better there is a constructor also with linkkost function object. dotlinker.setTrajectoryThreshold(5) dotlinker.setShowTrackTable(False) # dotlinker = DotLinker(loadmethod) linkcostfunction = dotlinker.setLinkCostFunction(lcAD) linkcostfunction.setParameters(5.0, 2.0)
def __calRois(self, imp, indice) : """ Returns the ROIs of a slice given (identified with its n°) in a stack """ ##imp=self.__dictImages[nameimages] # IL FAUT RÉCUPÉRER L'IMAGE DU STACK !!!!! #if self.__batch : imp.hide() #else : imp.show() #imp.hide() imp.show() if self.__batch : imp.hide() imp.setSlice(indice) imp.killRoi() ip = imp.getProcessor() bs=BackgroundSubtracter() #if str(self.__subback) == "0" or str(self.__subback) == "1" : self.__subback = bool(int(self.__subback)) #if self.__subback == True : IJ.run(imp, "Subtract Background...", "rolling="+str(self.__radius)+" light") if self.__subback == True : bs.rollingBallBackground(ip, self.__radius, False, True, False, True, False) if self.__runmacro : imp.show() imp.setSlice(indice) imp.updateAndDraw() IJ.runMacroFile(self.__macropath, imp.getTitle()) imp.updateAndDraw() #if str(self.__manthresh) == "0" or str(self.__manthresh) == "1" : self.__manthresh = bool(int(self.__manthresh)) #if self.__manthresh : IJ.setThreshold(imp, self.__minthr, self.__maxthr) if self.__manthresh : ip.setThreshold(self.__minthr, self.__maxthr, ImageProcessor.RED_LUT) else : self.__setThreshold(imp, indice) rt=ResultsTable() pa1=ParticleAnalyzer(ParticleAnalyzer.SHOW_MASKS+ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES , Measurements.AREA, rt, self.__minArea, self.__maxArea, self.__minCirc, self.__maxCirc) pa1.setHideOutputImage(True) pa1.analyze(imp) masks=pa1.getOutputImage() masks.getProcessor().erode() masks.getProcessor().dilate() masks.getProcessor().invertLut() masks.getProcessor().threshold(1) rm = RoiManager.getInstance() if (rm==None): rm = RoiManager() rm.runCommand("reset") #rm.hide() pa2=ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER+ParticleAnalyzer.CLEAR_WORKSHEET+ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES , Measurements.AREA, rt, self.__minArea, self.__maxArea, self.__minCirc, self.__maxCirc) pa2.analyze(masks) masks.close() temparray=rm.getRoisAsArray() for r in temparray : tempnameroi=r.getName() r.setPosition(indice) r.setName(str(indice)+"-"+tempnameroi) r.setStrokeWidth(1) if len(self.__params) > 0 : for k in self.__params: #if k[0]=="Area": self.__minArea, self.__maxArea = str(k[1]), str(k[2]) if k[0]=="Area": self.__minArea, self.__maxArea = k[1], k[2] for k in self.__params: #if k[0]=="Circ": self.__minCirc, self.__maxCirc = str(k[1]), str(k[2]) if (k[0]=="Circ") and k[3] : self.__minCirc, self.__maxCirc = k[1], k[2] else : self.__minCirc, self.__maxCirc = 0, 1 self.__rr.setRoisarray(temparray, imp) self.__rr.setRange(indice, self.__params) return self.__rr.includeRois else : return temparray
WaitForUserDialog("Title", "Adjust threshold").show() IJ.run(imp, "Convert to Mask", "") if not inverted: IJ.run(imp, "Invert", "") IJ.run(imp, "Fill Holes", "") if watershedMode: IJ.run(imp, "Watershed", "") #Measure particles table = ResultsTable() roim = RoiManager(True) ParticleAnalyzer.setRoiManager(roim) pa = ParticleAnalyzer( ParticleAnalyzer.ADD_TO_MANAGER | ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES, Measurements.AREA | Measurements.FERET | Measurements.CIRCULARITY | Measurements.SHAPE_DESCRIPTORS | Measurements.CENTROID | Measurements.ELLIPSE, table, minimum_size * pix_width, 9999999999999999, 0.2, 1.0) pa.setHideOutputImage(True) pa.analyze(imp) index = -1 maxArea = -1 if thresholdMode: imp.show()
def updatepressed(event): self.__image=IJ.getImage() rm = RoiManager.getInstance() if (rm==None): rm = RoiManager() rm.runCommand("reset") self.__image.killRoi() IJ.run("Threshold...") IJ.setAutoThreshold(self.__image, "MaxEntropy") rt=ResultsTable() pa=ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER+ParticleAnalyzer.CLEAR_WORKSHEET , Measurements.AREA+Measurements.ELLIPSE+Measurements.MEAN, rt, 0.00, 10000.00, 0.00, 1.00) pa.analyze(self.__image) self.__roisArray=[] self.__roisArray=rm.getRoisAsArray() #for i in range(rm.getCount()) : # rm.select(i) # rm.runCommand("Set Color", "0000FF", 2) IJ.resetThreshold(self.__image) rt.show("tempRT") areas=rt.getColumn(ResultsTable.AREA) means=rt.getColumn(ResultsTable.MEAN) majors=rt.getColumn(ResultsTable.MAJOR) minors=rt.getColumn(ResultsTable.MINOR) #print 0 if self.__slidersDict["Area_max"].getMaximum() < int(max(areas)+1): # print 1 self.__slidersDict["Area_max"].setMaximum(int(max(areas))+1) if self.__slidersDict["Area_min"].getMaximum() < int(max(areas)+1): # print 2 self.__slidersDict["Area_min"].setMaximum(int(max(areas))+1) if self.__slidersDict["Mean_max"].getMaximum() < int(max(means)+1): # print 3 self.__slidersDict["Mean_max"].setMaximum(int(max(means))+1) if self.__slidersDict["Mean_min"].getMaximum() < int(max(means)+1): # print 4 self.__slidersDict["Mean_min"].setMaximum(int(max(means))+1) if self.__slidersDict["Major_max"].getMaximum() < int(max(majors)): # print 5 self.__slidersDict["Major_max"].setMaximum(int(max(majors))+1) if self.__slidersDict["Major_min"].getMaximum() < int(max(majors)+1): # print 6 self.__slidersDict["Major_min"].setMaximum(int(max(majors))+1) if self.__slidersDict["Minor_max"].getMaximum() < int(max(minors)+1): # print 7 self.__slidersDict["Minor_max"].setMaximum(int(max(minors))+1) if self.__slidersDict["Minor_min"].getMaximum() < int(max(minors)+1): # print 8 self.__slidersDict["Minor_min"].setMaximum(int(max(minors))+1) if self.__slidersDict["AR_max"].getMaximum() < int((max(majors)+1)/min(minors)+1): # print 9 self.__slidersDict["AR_max"].setMaximum(int((max(majors)+1)/(min(minors)))) if self.__slidersDict["AR_min"].getMaximum() < int((max(majors)+1)/min(minors)): # print 10 self.__slidersDict["AR_min"].setMaximum(int((max(majors)+1)/(min(minors)))) #print 11 for sb in self.__slidersDict.values(): sb.repaint() #rm.runCommand("reset") #temprois=self.getIncludeRois() #IJ.run(self.__image, "Remove Overlay", "") #o=Overlay() #for roi in temprois: # o.addElement(roi) #self.__image.killRoi() #self.__image.setOverlay(o) self.__image.updateAndDraw()
from ij.measure import ResultsTable from ij.measure import Measurements from ij.plugin.frame import RoiManager from ij.plugin.filter import ParticleAnalyzer from ij import IJ # get active image imp = IJ.getImage() # set up first ROI manager table1 = ResultsTable() roim1 = RoiManager() pa1 = ParticleAnalyzer( ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA | Measurements.MEAN | Measurements.ELLIPSE, table1, 0, 100, 0, 1) pa1.setRoiManager(roim1) pa1.analyze(imp) # set up second ROI manager table2 = ResultsTable() # Pass true to second ROI manager so it will not be seen roim2 = RoiManager(True) pa2 = ParticleAnalyzer( ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA | Measurements.MEAN | Measurements.ELLIPSE, table2, 100, 500, 0, 1) pa2.setRoiManager(roim2) pa2.analyze(imp) print "rois from first manager:"
BS.rollingBallBackground(dapi_ip, *[a[1] for a in bkgd_sub]) if SHOW_IMAGES: dapi.updateAndDraw() # IJ.setAutoThreshold("Otsu"); # IJ.run("Convert to Mask"); dapi_ip.autoThreshold() dapi.setProcessor(dapi_ip.convertToByteProcessor(False)) dapi_ip = dapi.getProcessor() # IJ.run("Watershed"); EDM().toWatershed(dapi_ip) dapi_ip.invert() # IJ.run("Analyze Particles...", "size=30-400 show=Masks"); pa_options = particle_analyzer(dapi.getCalibration().pixelWidth) PA = ParticleAnalyzer(*[a[1] for a in pa_options]) PA.analyze(dapi, dapi_ip) if SHOW_IMAGES: dapi.updateAndDraw() IJ.save(dapi, savename(stack)) dapi.close() rename_file(progress_name, done_name) print 'done'
def process(subFolder, outputDirectory, filename): #IJ.close() imp = IJ.openImage(inputDirectory + subFolder + '/' + rreplace(filename, "_ch00.tif", ".tif")) imp.show() IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) ic = ImageConverter(imp) ic.convertToGray8() #IJ.setThreshold(imp, 2, 255) #Automatically selects the area of the organoid based on automated thresholding and creates a mask to be applied on #all other images IJ.setAutoThreshold(imp, "Mean dark no-reset") IJ.run(imp, "Convert to Mask", "") IJ.run(imp, "Analyze Particles...", "size=100000-Infinity add select") rm = RoiManager.getInstance() imp = getCurrentImage() rm.select(imp, 0) IJ.setBackgroundColor(0, 0, 0) IJ.run(imp, "Clear Outside", "") IJ.run(imp, "Convert to Mask", "") IJ.run(imp, "Remove Outliers...", "radius=5" + " threshold=50" + " which=Dark") IJ.run(imp, "Remove Outliers...", "radius=5" + " threshold=50" + " which=Bright") # #Save the mask and open it IJ.saveAs("tiff", inputDirectory + '/mask') mask = IJ.openImage(inputDirectory + '/mask.tif') if not displayImages: imp.changes = False imp.close() images = [None] * 5 intensities = [None] * 5 blobsarea = [None] * 5 blobsnuclei = [None] * 5 bigAreas = [None] * 5 imp.close() #Loop to open all the channel images for chan in channels: v, x = chan images[x] = IJ.openImage(inputDirectory + subFolder + '/' + rreplace(filename, "_ch00.tif", "_ch0" + str(x) + ".tif")) # Apply Mask on all the images and save them into an array apply_mask = ImageCalculator() images[x] = apply_mask.run("Multiply create 32 bit", mask, images[x]) ic = ImageConverter(images[x]) ic.convertToGray8() imp = images[x] # Calculate the intensities for each channel as well as the organoid area for roi in rm.getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.MEAN | Measurements.AREA) intensities[x] = stats.mean bigAreas[x] = stats.area rm.close() # Opens the ch00 image and sets default properties imp = IJ.openImage(inputDirectory + subFolder + '/' + filename) imp = apply_mask.run("Multiply create 32 bit", mask, imp) IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) # Sets the threshold and watersheds. for more details on image processing, see https://imagej.nih.gov/ij/developer/api/ij/process/ImageProcessor.html ic = ImageConverter(imp) ic.convertToGray8() IJ.run(imp, "Remove Outliers...", "radius=2" + " threshold=50" + " which=Dark") IJ.run(imp, "Gaussian Blur...", "sigma=" + str(blur)) IJ.setThreshold(imp, lowerBounds[0], 255) if displayImages: imp.show() IJ.run(imp, "Convert to Mask", "") IJ.run(imp, "Watershed", "") if not displayImages: imp.changes = False imp.close() # Counts and measures the area of particles and adds them to a table called areas. Also adds them to the ROI manager table = ResultsTable() roim = RoiManager(True) ParticleAnalyzer.setRoiManager(roim) pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA, table, 15, 9999999999999999, 0.2, 1.0) pa.setHideOutputImage(True) # imp = impM # imp.getProcessor().invert() pa.analyze(imp) areas = table.getColumn(0) # This loop goes through the remaining channels for the other markers, by replacing the ch00 at the end with its corresponding channel # It will save all the area fractions into a 2d array called areaFractionsArray areaFractionsArray = [None] * 5 for chan in channels: v, x = chan # Opens each image and thresholds imp = images[x] IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) ic = ImageConverter(imp) ic.convertToGray8() IJ.setThreshold(imp, lowerBounds[x], 255) if displayImages: imp.show() WaitForUserDialog("Title", "Adjust Threshold for Marker " + v).show() IJ.run(imp, "Convert to Mask", "") # Measures the area fraction of the new image for each ROI from the ROI manager. areaFractions = [] for roi in roim.getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.AREA_FRACTION) areaFractions.append(stats.areaFraction) # Saves the results in areaFractionArray areaFractionsArray[x] = areaFractions roim.close() for chan in channels: v, x = chan imp = images[x] imp.deleteRoi() roim = RoiManager(True) ParticleAnalyzer.setRoiManager(roim) pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA, table, 15, 9999999999999999, 0.2, 1.0) pa.analyze(imp) blobs = [] for roi in roim.getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.AREA) blobs.append(stats.area) blobsarea[x] = sum( blobs ) #take this out and use intial mask tissue area from the beginning blobsnuclei[x] = len(blobs) if not displayImages: imp.changes = False imp.close() roim.reset() roim.close() imp.close() # Creates the summary dictionary which will correspond to a single row in the output csv, with each key being a column summary = {} summary['Image'] = filename summary['Directory'] = subFolder # Adds usual columns summary['size-average'] = 0 summary['#nuclei'] = 0 summary['all-negative'] = 0 summary['too-big-(>' + str(tooBigThreshold) + ')'] = 0 summary['too-small-(<' + str(tooSmallThreshold) + ')'] = 0 # Creates the fieldnames variable needed to create the csv file at the end. fieldnames = [ 'Name', 'Directory', 'Image', 'size-average', 'too-big-(>' + str(tooBigThreshold) + ')', 'too-small-(<' + str(tooSmallThreshold) + ')', '#nuclei', 'all-negative' ] # Adds the columns for each individual marker (ignoring Dapi since it was used to count nuclei) summary["organoid-area"] = bigAreas[x] fieldnames.append("organoid-area") for chan in channels: v, x = chan summary[v + "-positive"] = 0 fieldnames.append(v + "-positive") summary[v + "-intensity"] = intensities[x] fieldnames.append(v + "-intensity") summary[v + "-blobsarea"] = blobsarea[x] fieldnames.append(v + "-blobsarea") summary[v + "-blobsnuclei"] = blobsnuclei[x] fieldnames.append(v + "-blobsnuclei") # Adds the column for colocalization between first and second marker if len(channels) > 2: summary[channels[1][0] + '-' + channels[2][0] + '-positive'] = 0 fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-positive') # Adds the columns for colocalization between all three markers if len(channels) > 3: summary[channels[1][0] + '-' + channels[3][0] + '-positive'] = 0 summary[channels[2][0] + '-' + channels[3][0] + '-positive'] = 0 summary[channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive'] = 0 fieldnames.append(channels[1][0] + '-' + channels[3][0] + '-positive') fieldnames.append(channels[2][0] + '-' + channels[3][0] + '-positive') fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive') # Loops through each particle and adds it to each field that it is True for. areaCounter = 0 for z, area in enumerate(areas): log.write(str(area)) log.write("\n") if area > tooBigThreshold: summary['too-big-(>' + str(tooBigThreshold) + ')'] += 1 elif area < tooSmallThreshold: summary['too-small-(<' + str(tooSmallThreshold) + ')'] += 1 else: summary['#nuclei'] += 1 areaCounter += area temp = 0 for chan in channels: v, x = chan if areaFractionsArray[x][z] > areaFractionThreshold[ 0]: # theres an error here im not sure why. i remember fixing it before summary[chan[0] + '-positive'] += 1 if x != 0: temp += 1 if temp == 0: summary['all-negative'] += 1 if len(channels) > 2: if areaFractionsArray[1][z] > areaFractionThreshold[1]: if areaFractionsArray[2][z] > areaFractionThreshold[2]: summary[channels[1][0] + '-' + channels[2][0] + '-positive'] += 1 if len(channels) > 3: if areaFractionsArray[1][z] > areaFractionThreshold[1]: if areaFractionsArray[3][z] > areaFractionThreshold[3]: summary[channels[1][0] + '-' + channels[3][0] + '-positive'] += 1 if areaFractionsArray[2][z] > areaFractionThreshold[2]: if areaFractionsArray[3][z] > areaFractionThreshold[3]: summary[channels[2][0] + '-' + channels[3][0] + '-positive'] += 1 if areaFractionsArray[1][z] > areaFractionThreshold[1]: summary[channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive'] += 1 # Calculate the average of the particles sizes if float(summary['#nuclei']) > 0: summary['size-average'] = round(areaCounter / summary['#nuclei'], 2) # Opens and appends one line on the final csv file for the subfolder (remember that this is still inside the loop that goes through each image) with open(outputDirectory + "/" + outputName + ".csv", 'a') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames, extrasaction='ignore', lineterminator='\n') if os.path.getsize(outputDirectory + "/" + outputName + ".csv") < 1: writer.writeheader() writer.writerow(summary) IJ.run(imp, "Close All", "")
blueImp = ImagePlus("blue", channels[2]) blueImp.getProcessor().invert() blueImp.show() WindowManager.setTempCurrentImage(blueImp) IJ.run("Make Binary") blueImp.hide() roim = RoiManager(True) # Create a ParticleAnalyzer, with arguments: # 1. options (could be SHOW_ROI_MASKS, SHOW_OUTLINES, SHOW_MASKS, SHOW_NONE, ADD_TO_MANAGER, and others; combined with bitwise-or) # 2. measurement options (see [http://rsb.info.nih.gov/ij/developer/api/ij/measure/Measurements.html Measurements]) # 3. a ResultsTable to store the measurements # 4,5. The min and max size of a particle to consider for measurement # 6,7. The min and max circularity (values between 0 and 1 perfect circle) pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA, None, 200, 4000, 0.4, 1.0) pa.setHideOutputImage(True) if pa.analyze(blueImp): print "All ok" else: print "There was a problem in analyzing", blueImp #Export roi center and radius to TSV default_name = imp.getShortTitle() + "_cells" sd = SaveDialog('Save ellypses to file', default_name, '.tsv') dirToSave = sd.getDirectory() fileh = open(dirToSave + sd.getFileName(), "w") #fileh.write("name\tx1\tx2\ty1\ty2\n") roim = RoiManager.getInstance()
def process(self,imp): # extract nucleus channel, 8-bit and twice binned imp.setC(self.nucleusChannel) ip = imp.getChannelProcessor().duplicate() ip = ip.convertToByteProcessor() ip = ip.bin(4) nucleus = ImagePlus("nucleus_channel", ip) # threshold image and separate clumped nuclei IJ.run(nucleus, "Auto Threshold", "method=Otsu white setthreshold show"); IJ.run(nucleus, "Make Binary", "thresholded remaining black"); IJ.run(nucleus, "Watershed", ""); directory = imp.getTitle() directory = directory.replace(" ", "_")\ .replace(",", "_")\ .replace("#", "_series")\ .replace("...", "")\ .replace(".","_") directory = os.path.join(self.exportDir, directory) sliceDirectory = os.path.join(directory, "slices") print directory print sliceDirectory if not os.path.exists(sliceDirectory): os.makedirs(sliceDirectory) # 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) # remove small particles and border particles pa = ParticleAnalyzer(\ ParticleAnalyzer.ADD_TO_MANAGER | ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES,\ Measurements.CENTER_OF_MASS,\ table,\ self.minArea, self.maxArea,\ 0.0,1.0) if pa.analyze(nucleus): print "All ok, number of particles: ", table.size() else: print "There was a problem in analyzing", imp, nucleus table.save(os.path.join(directory, "rt.csv")) # read the center of mass coordinates cmx = table.getColumn(0) cmy = table.getColumn(1) if self.debug: imp.show() i=0 for i in range(0, min(self.nCells,table.size())): # ROI around the cell cmx = table.getValue("XM",i) cmy = table.getValue("YM",i) x = 4 * cmx - (self.boxSize - 1) / 2 y = 4 * cmy - (self.boxSize - 1) / 2 if (x < self.edge or y < self.edge or x > imp.getWidth() - self.edge or y > imp.getHeight() - self.edge): continue roi = Roi(x,y,self.boxSize,self.boxSize) imp.setRoi(roi, False) cellStack = ImageStack(self.boxSize, self.boxSize) for z in range(1, imp.getNSlices() + 1): imp.setSlice(z) for c in range(1, imp.getNChannels() + 1): imp.setC(c) # copy ROI to stack imp.copy() impSlice = imp.getClipboard() cellStack.addSlice(impSlice.getProcessor()) if self.slices: sliceTitle = "cell_%s_z%s_c%s" % (str(i).zfill(4), str(z).zfill(3), str(c)) print sliceTitle IJ.saveAsTiff(impSlice, os.path.join(sliceDirectory, sliceTitle)) impSlice.close() title = "cell_" + str(i).zfill(4) cell = ImagePlus(title, cellStack) # save ROI image IJ.saveAsTiff(cell, os.path.join(directory, title)) cell.close() if self.debug: imp.updateAndDraw() wait = Wait("particle done") wait.show()
def nucleusSegmentation(imp2): """ Segmentation of nucleus image. Nucleus are selected that: 1. No overlapping with dilated regions 2. close to circular shape. Deformed nuclei are rejected. Outputs a binary image. """ #Convert to 8bit ImageConverter(imp2).convertToGray8() #blur slightly using Gaussian Blur radius = 2.0 accuracy = 0.01 GaussianBlur().blurGaussian( imp2.getProcessor(), radius, radius, accuracy) # Auto Local Thresholding imps = ALT().exec(imp2, "Bernsen", 15, 0, 0, True) imp2 = imps[0] #ParticleAnalysis 0: prefiltering by size and circularity rt = ResultsTable() paOpt = PA.CLEAR_WORKSHEET +\ PA.SHOW_MASKS +\ PA.EXCLUDE_EDGE_PARTICLES +\ PA.INCLUDE_HOLES #+ \ # PA.SHOW_RESULTS measOpt = PA.AREA + PA.STD_DEV + PA.SHAPE_DESCRIPTORS + PA.INTEGRATED_DENSITY MINSIZE = 20 MAXSIZE = 10000 pa0 = PA(paOpt, measOpt, rt, MINSIZE, MAXSIZE, 0.8, 1.0) pa0.setHideOutputImage(True) pa0.analyze(imp2) imp2 = pa0.getOutputImage() # Overwrite imp2.getProcessor().invertLut() #impNuc = imp2.duplicate() ## for the ring. impNuc = Duplicator().run(imp2) #Dilate the Nucleus Area ## this should be 40 pixels in Cihan's method, but should be smaller. #for i in range(20): # IJ.run(imp2, "Dilate", "") rf = RankFilters() rf.rank(imp2.getProcessor(), RIMSIZE, RankFilters.MAX) #Particle Analysis 1: get distribution of sizes. paOpt = PA.CLEAR_WORKSHEET +\ PA.SHOW_NONE +\ PA.EXCLUDE_EDGE_PARTICLES +\ PA.INCLUDE_HOLES #+ \ # PA.SHOW_RESULTS measOpt = PA.AREA + PA.STD_DEV + PA.SHAPE_DESCRIPTORS + PA.INTEGRATED_DENSITY rt1 = ResultsTable() MINSIZE = 20 MAXSIZE = 10000 pa = PA(paOpt, measOpt, rt1, MINSIZE, MAXSIZE) pa.analyze(imp2) #rt.show('after PA 1') #particle Analysis 2: filter nucleus by size and circularity. #print rt1.getHeadings() if (rt1.getColumnIndex('Area') > -1): q1, q3, outlier_offset = getOutlierBound(rt1) else: q1 = MINSIZE q3 = MAXSIZE outlier_offset = 0 print imp2.getTitle(), ": no Nucleus segmented,probably too many overlaps" paOpt = PA.CLEAR_WORKSHEET +\ PA.SHOW_MASKS +\ PA.EXCLUDE_EDGE_PARTICLES +\ PA.INCLUDE_HOLES #+ \ # PA.SHOW_RESULTS rt2 = ResultsTable() #pa = PA(paOpt, measOpt, rt, q1-outlier_offset, q3+outlier_offset, circq1-circoutlier_offset, circq3+circoutlier_offset) pa = PA(paOpt, measOpt, rt2, q1-outlier_offset, q3+outlier_offset, 0.8, 1.0) pa.setHideOutputImage(True) pa.analyze(imp2) impDilatedNuc = pa.getOutputImage() #filter original nucleus filteredNuc = ImageCalculator().run("AND create", impDilatedNuc, impNuc) return filteredNuc
if VERBOSE: binorg.show() # Count nucleus setting MAXSIZE = imp3.getWidth()*imp3.getHeight(); MINSIZE = 100; #options = PA.SHOW_ROI_MASKS \ # + PA.EXCLUDE_EDGE_PARTICLES \ # + PA.INCLUDE_HOLES \ # + PA.SHOW_RESULTS \ options = PA.INCLUDE_HOLES \ + PA.CLEAR_WORKSHEET \ # + PA.SHOW_RESULTS \ rt = ResultsTable() p = PA(options, PA.AREA + PA.STACK_POSITION, rt, MINSIZE, MAXSIZE) p.setHideOutputImage(True) # Morphological dilate binner.setup('dilate', None) clusters = 0 initialCells = 0 # dilate by 'SAMPLEITER' for i in range(SAMPLEITER+1): p.analyze(binimp) cellcounts = rt.getCounter() if i == 0: initialCells = cellcounts
import ij from ij import IJ import ij.plugin import ij.gui import ij.measure from ij.plugin.filter import ParticleAnalyzer as PA # Make the background black...I'm not sure why it doesn't do this automatically! IJ.run("Options...", "iterations=1 black count=1") options = PA.FOUR_CONNECTED + \ PA.INCLUDE_HOLES + \ PA.SHOW_OUTLINES rt = ij.measure.ResultsTable() analyzer = PA(options, PA.AREA, rt, 0, 10**9) image = IJ.getImage() analyzer.analyze(image) #IJ.run("Analyze Particles...", "include add slice");
for img_ind, image in enumerate(proc_images): imp = IJ.openImage(image) imp.show() IJ.setThreshold(128, 128) #rm = None#RoiManager.getInstance() if not rm: rm = RoiManager() else: rm.reset() #IJ.run(imp,"Analyze Particles...", "size=112-Infinity exclude add") rt = ResultsTable() pa = ParticleAnalyzer(EXCLUDE_EDGE_PARTICLES | ADD_TO_MANAGER, 0, rt, 800, float('inf'), 0.0, 1.0) pa.analyze(imp) # time.sleep(2) print 'Size of results: ', rt.size() # rm.runCommand("select","all") # rm.runCommand("Fill","3") save_path = saving_dir + "/mask_%s" % (image[image.rindex('/') + 1:]) # print(save_path) impMask = IJ.createImage("Mask", "8-bit grayscale-mode", imp.getWidth(), imp.getHeight(), imp.getNChannels(), imp.getNSlices(), imp.getNFrames()) impMask.show() IJ.setForegroundColor(255, 255, 255) rm.runCommand(impMask, "Deselect")
from ij.measure import ResultsTable from ij.measure import Measurements from ij.plugin.frame import RoiManager from ij.plugin.filter import ParticleAnalyzer from ij import IJ # get active image imp=IJ.getImage() # set up first ROI manager table1 = ResultsTable() roim1=RoiManager() pa1 = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA|Measurements.MEAN|Measurements.ELLIPSE, table1, 0, 100, 0, 1) pa1.setRoiManager(roim1) pa1.analyze(imp) # set up second ROI manager table2 = ResultsTable() # Pass true to second ROI manager so it will not be seen roim2=RoiManager(True) pa2 = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA|Measurements.MEAN|Measurements.ELLIPSE, table2, 100, 500, 0, 1) pa2.setRoiManager(roim2) pa2.analyze(imp) print "rois from first manager:" for roi in roim1.getRoisAsArray(): print roi print print "rois from second manager:" for roi in roim2.getRoisAsArray(): print roi