本文整理汇总了Python中ij.plugin.frame.RoiManager类的典型用法代码示例。如果您正苦于以下问题:Python RoiManager类的具体用法?Python RoiManager怎么用?Python RoiManager使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了RoiManager类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: measureTumor
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)
示例2: resetpressed
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()
示例3: __init__
def __init__(self):
swing.JFrame.__init__(self, title="Stack Cells")
self.__impD = IJ.getImage()
self.setDefaultCloseOperation(swing.JFrame.DISPOSE_ON_CLOSE)
self.__n=0
self.__widthl = "11"
self.__iplist = []
self.__init = False
self.__initDIA = False
self.__initFLUO = False
self.__skip = False
self.__avg = True
self.__mosa = True
self.__maxfinder = True
self.__appmedian = True
self.__fire = True
self.__align = True
self.__alignC = False
self.__enlarge = True
self.__measures = True
self.__sens = []
self.__listrois = []
self.__cellsrois = []
self.__Cutoff = 0
self.__labels = []
self.__maxraf = 100.0
self.__minraf = 0.0
self.__conEllipses = False
self.__dictCells = {}
self.__rm = RoiManager.getInstance()
if (self.__rm==None): self.__rm = RoiManager()
self.run()
示例4: get_roi_manager
def get_roi_manager(new=False):
rm = RoiManager.getInstance()
if not rm:
rm = RoiManager()
if new:
rm.runCommand("Reset")
return rm
示例5: __add
def __add(self, event):
if ( not self.__init) :
IJ.showMessage("", "please start a new stack")
return
if ( not self.__initDIA) :
IJ.showMessage("", "please select an image for DIA")
return
if ( not self.__initFLUO) :
IJ.showMessage("", "please select an image for FLUO")
return
self.__widthl = self.__display2.getText()
roi = self.__impD.getRoi()
if roi == None :
IJ.showMessage("", "No selection")
return
if roi.getType() in [6,7] :
nslice = self.__impD.getCurrentSlice()
self.__impF.setSlice(nslice)
self.__impF.setRoi(roi)
elif roi.getType() in [2,4] :
nslice = self.__impD.getCurrentSlice()
self.__impF.setSlice(nslice)
m=Morph(self.__impF, roi)
m.setMidParams(10, 2)
roi=m.MidAxis
if roi == None :
self.__display.text = "roi fail"
if not self.__skip : IJ.showMessage("", "failed roi, please draw it as polyline")
return
#if roi.getType() != 6 : self.__impF.setRoi(roi)
else :
IJ.showMessage("", "This selection is not yet allowed")
return
self.__impF.setRoi(roi)
straightener = Straightener()
new_ip = straightener.straighten(self.__impF, roi, int(self.__widthl))
self.__iplist.append(new_ip)
self.__labels.append(self.__isF.getShortSliceLabel(nslice))
self.__display.text = self.__name + " cell " + str(len(self.__iplist)) +" width="+str(new_ip.getWidth())+ " height="+ str(new_ip.getHeight())
roi.setPosition(self.__impD.getCurrentSlice())
self.__rm = RoiManager.getInstance()
if (self.__rm==None): self.__rm = RoiManager()
self.__rm.add(self.__impD, roi, len(self.__iplist))
self.__cellsrois.append((roi, self.__impD.getCurrentSlice()))
#self.__rm.runCommand("Show All")
IJ.selectWindow(self.__impD.getTitle())
示例6: particleRemover
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");
示例7: anaParticlesWatershed
def anaParticlesWatershed(imp, strThrMeth="method=Default white", minPx=10, minCirc=0.35, labCol=Color.white, linCol=Color.green, bDebug=False, sl=0.005):
"""anaParticlesWatershed(imp, strThrMeth="method=Default white", minPx=10, minCirc=0.35, labCol=Color.white, linCol=Color.green, bDebug=False, sl=0.005)
A wrapper function to do particle analyis from an image after a watershed transformation and draw the detected
features into the overlay of the original image.
Inputs:
imp - the ImagePlus instance that we will process
strThrMeth - a string specifying the threshold method
minPx - the minimum pixels to detect
minCirc - the minimum circularity to detect
labCol - the color for labels in the overlay (default white)
linCol - the color for line/stroke in the overlay (default green)
bDebug - a flag (default False) that, if true, keeps the work image open
sl - a time (default 0.005) to sleep when adding ROIs to not overload
This adds the detected features to the overlay and returns the result table for
processing for output.
"""
title = imp.getTitle()
shortTitle = imp.getShortTitle()
typ = imp.getType()
imp.setTitle(shortTitle)
imp.show()
IJ.run(imp,"Duplicate...", "title=work")
wrk = IJ.getImage()
# if this is a 16 bit image, convert to 8 bit prior to threshold
if typ == ImagePlus.GRAY16:
IJ.run(wrk, "Enhance Contrast", "saturated=0.35")
IJ.run(wrk, "8-bit", "")
IJ.run(wrk, "Threshold", strThrMeth)
IJ.run(wrk, "Watershed", "")
wrk.show()
strMeas = "area mean modal min center perimeter bounding fit shape feret's display redirect=%s decimal=3" % shortTitle
IJ.run(wrk, "Set Measurements...", strMeas)
strAna = "size=%d-Infinity circularity=%g-1.00 exclude clear include add" % (minPx, minCirc)
IJ.run(wrk, "Analyze Particles...", strAna)
rt = ResultsTable().getResultsTable()
rm = RoiManager.getInstance()
ra = rm.getRoisAsArray()
# Let's draw the particles into the overlay of the original
i=0
for r in ra:
i += 1
rLab = "%d" % i
r.setName(rLab)
imp = addRoiToOverlay(imp, r, labCol=labCol, linCol=linCol)
# needed to put in sleep here on cruch to let this complete and not overrun buffer
time.sleep(sl)
# let's put a PointRoi outside the image to get the overlays all the same color
r = PointRoi(-10, -10)
imp = addRoiToOverlay(imp, r, labCol=labCol, linCol=linCol)
# clear the roi manager and return the results table
rm.reset()
rm.close()
if bDebug == False:
wrk.changes = False
wrk.close()
imp.setTitle(title)
return rt
示例8: segmentChannel_Weka
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
开发者ID:tischi,项目名称:scripts,代码行数:50,代码来源:2015-04-30--Tischi--KatharinaSonnen--Online_Weka_Metaphase_Detection_.py
示例9: grab
def grab(self, dialog_options=None):
""" Get the image patches using the ROI manager.
"""
if not dialog_options:
return
# get a refence to the ROI manager and check that we have ROIs!
rm = RoiManager.getRoiManager()
num_ROIs = rm.getCount()
if num_ROIs < 1: return None
if dialog_options['rename']:
for r in xrange(num_ROIs):
rm.getRoi(r).setName('{0:s}_{1:s}_{2:d}'.format(self.session_id,dialog_options['label'],r))
return [ClassifierROI(rm.getRoi(r), path=dialog_options['path']) for r in xrange(num_ROIs)]
示例10: filter_hough
def filter_hough():
new_image = IJ.getImage()
# Get the roi manager
roi_manager = RoiManager.getInstance()
roi_array = roi_manager.getRoisAsArray()
for cur_roi in roi_array:
new_image.setRoi(cur_roi)
stats = new_image.getStatistics(Measurements.CENTROID)
x_centroid_list.append(stats.xCentroid)
y_centroid_list.append(stats.yCentroid)
# Close the new image
new_image.killRoi() # Remove the remaining ROI
roi_manager.runCommand("Reset")
roi_manager.runCommand("Close")
new_image.changes = False
new_image.close()
示例11: ShowRoi
def ShowRoi(self,imp,point, name):
for indices in self.__gridrectangle.keys() :
if self.__gridrectangle[indices].contains(point) :
roitemp=self.__dictCells[name][self.__listcellname[indices[0]-1]].getRoi(indices[1]-1)
if isinstance(roitemp,Roi) :
idimages=WindowManager.getIDList()
for i in range(len(idimages)) :
if idimages[i]==self.__img.getID() :
IJ.selectWindow(self.__img.getID())
rm = RoiManager.getInstance()
for i in range(rm.getCount()) :
if rm.getName(str(i))==roitemp.getName() :
rm.select(i)
selectroi=self.__img.getRoi()
#col=rm.getSelectedRoisAsArray().getStrokeColor()
selectroi.setStrokeColor(Color.red)
selectroi.setStrokeWidth(3)
self.__img.updateAndDraw()
break
示例12: write
def write(self, ROIs=None, dialog_options=None):
""" Write out the classifier info
"""
if not dialog_options or not isinstance(ROIs, list):
return
# get the data stack
channels = ['BF', 'GFP', 'RFP']
channels_to_use = [c for c in channels if dialog_options[c] != 'None']
print channels_to_use
for c in channels_to_use:
for r in ROIs:
IJ.log("Grabbing patches for ROI: "+ r.name)
r.window_size = dialog_options['window_size']
r.save = dialog_options['save']
r(data=WindowManager.getImage(dialog_options[c]), channel=c)
if dialog_options['zip']:
roi_fn = os.path.join(dialog_options['path'], dialog_options['label']+'_'+str(self.session_id)+'_ROIset.zip')
rm = RoiManager.getRoiManager()
rm.runCommand('Select All')
rm.runCommand('Save', roi_fn)
# old style dictionary comprehension
ROI_dict = dict((r.name,{'frame':r.index, 'x':r.x, 'y':r.y}) for r in ROIs)
ROI_dict['opts'] = dialog_options
# save out a pickled dictionary with all of the details
if dialog_options['save']:
pass
# try:
# classifier_file = open(os.path.join(dialog_options['path'],dialog_options['data']+'_classifier.p'), 'wb')
# pickle.dump( ROI_dict, classifier_file, -1)
# classifier_file.close()
# except IOError:
# IJ.log('Could not pickle classifier info file.')
print ROI_dict
示例13: MandersColocalization
chimps.append(proj)
return RGBStackMerge.mergeChannels(chimps, False)
manders = MandersColocalization()
results = ResultsTable()
for imageFile in os.listdir(inputDir):
print "Opening " + imageFile
try:
images = BF.openImagePlus(inputDir + imageFile)
image = images[0]
except UnknownFormatException:
continue
preview = getPreview(image)
preview.show()
rm = RoiManager()
dialog = WaitForUserDialog("Action required", "Please select regions of interest in this image. Click OK when done.")
dialog.show()
rm.close()
splitter = ChannelSplitter()
imp1 = ImagePlus("CH1", splitter.getChannel(image, imageA))
imp2 = ImagePlus("CH2", splitter.getChannel(image, imageB))
title = image.getTitle()
title = title[:title.rfind('.')]
image.close()
preview.close()
ch1 = ImagePlusAdapter.wrap(imp1)
ch2 = ImagePlusAdapter.wrap(imp2)
for roi in rm.getRoisAsArray():
container = createContainer(roi, ch1, ch2)
示例14: updatepressed
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()
示例15: showSettingsDialog
def showSettingsDialog(self):
if self.__image.getOverlay() is not None : self.__image.getOverlay().clear()
rm = RoiManager.getInstance()
if (rm==None): rm = RoiManager()
#rm.runCommand("Deselect")
#for i in range(rm.getCount()) :
# rm.select(i)
# rm.runCommand("Set Color", "0000FF", 2)
IJ.resetThreshold(self.__image)
rm.runCommand("Show All")
self.__ranges.clear()
#areas, means, majors, minors=[],[],[],[]
#for roi in self.__roisArray:
# m=Morph(self.__image, roi)
# areas.append(m.Area)
# means.append(m.Mean)
# majors.append(m.Major)
# minors.append(m.Minor)
#maxarea=max(areas)*1000
#maxint=max(means)*10
#maxline=max(majors)*100
#maxminline=max(minors)*100
#minline=min(minors)
#namemeasures=["Area", "Mean", "Angle", "Major", "Minor", "Solidity", "AR", "Round", "Circ"]
#maxmeasures=[maxarea, maxint, 180*10, maxline, maxminline, 1*1000, (maxline/minline), 1*1000, 1*1000]
#set1000=Set(["Solidity", "Round", "Circ"])
#set10=Set(["Angle"])
def buttonPressed(event):
temprois=self.getIncludeRois()
for roi in temprois:
m=Morph(self.__image, roi)
IJ.log("----------------------------------")
IJ.log(roi.getName())
for r in self.__ranges.values():
IJ.log(r[0]+" min= "+str(r[1])+" < val="+str(m.__getattribute__(r[0]))+" < max= "+str(r[2]))
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()
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)
#.........这里部分代码省略.........