Skip to main content
 首页 » 编程设计

python之仅获取 ROI 中的像素,如何

2025年05月04日9lidabo

尝试编写脚本,到目前为止,我有一个函数可以返回通过阈值得出的 ROI。

PA.setRoiManager(roim) 
paOpt = PA.CLEAR_WORKSHEET +PA.SHOW_NONE +PA.INCLUDE_HOLES +PA.EXCLUDE_EDGE_PARTICLES + PA.ADD_TO_MANAGER  
# measurement options: clear the results, show nothing, include holes, exclude particles on edges and add ROIs to manager 
measOpt = PA.AREA + PA.MEAN + PA.MIN_MAX # measure the minimum, maximum, mean and area of particles           
pa = PA(paOpt, measOpt, rt, minSize, maxSize) 
pa.analyze(imp) 
roi_list = roim.getRoisAsArray() 
print roi_list[0]  

这会向控制台输出:Roi[Traced, x=, y=, width=, height= ] 所以我有信心找到投资返回率。 roim 是 RoiManager 的一个实例。

现在的问题是当我去查看 ROI 内的像素时。

def pixelStats(roiPatch, imp): 
  ''' 
  get the pixel value distribution for the patch ROI  
  return the number of Lo pixels and the number of Ld pixels  
  roi_Patch returns handle to the patch ROI and imp is the  
  instance of current ImagePlus to be measured 
  ''' 
  mask = roiPatch.getMask() # mask of roiPatch, do you need this? 
  ip = imp.getProcessor()  
  ip.setRoi(roiPatch) 
  cal = imp.getCalibration() 
  # options = IS.MEAN | IS.STD_DEV | IS.MODE 
  stats = IS.getStatistics(ip, M.MEAN | M.MODE | M.STD_DEV, cal) # what does getCalibration do??? stats for ROI only applied to imp, why? 
  # see the following --> http://fiji.sc/Jython_Scripting#Obtain.2FView_histogram_and_measurements_from_an_image 
  domThreshold = stats.mode - stats.STD_DEV  
  backGround = stats.MEAN - stats.STD_DEV  
  # define the threshold for Lo/Ld phase  
  pixels = ip.getPixels()  
  above = filter(lambda i: pixels[i] > backGround, xrange(len(pixels))) 
  below = filter(lambda i: above[i] < domThreshold, xrange(len(above))) 
  # calculate the length of the arrays containing pixels of Lo/Ld phase  
  return len(above), len(below), len(pixels) 

查看返回的测量值,我确信 ip.getPixels() 只是从原始图像处理器返回像素,而不仅仅是 ROI。换句话说,我只是得到原始“矩形”图像中的像素数。

谁能说说这是为什么?或者提出做同样事情的更好方法。

请您参考如下方法:

我熟悉 Java API 但不熟悉 python,所以我的答案没有经过测试。

方法

ip.getPixels()  

正在做我期望的事情并返回所有像素。是否有投资返回率并不影响这一点。您的测量会考虑 ROI,因此均值和众数是根据您设置的 ROI 计算的。

为了解决这个问题,我会裁剪 ip。应该有一个

ip.crop()  

将返回 ip 的方法考虑了 ROI,然后您可以调用该方法

ip.getPixels() 

只获取ROI中的像素。