Skip to main content
 首页 » 编程设计

python之Scipy 标签并测量每个标签中的最大像素

2025年05月04日8bonelee

所以我想使用 scipy 测量每个标签(在多个数组中)的最大像素和平均像素。 例如

(img,其他是打开的tif的numpy数组)

import numpy as np 
import scipy.ndimage as ndi 
 
a = img > 200 
labels,nb = ndi.labels(a) 
 
merge = np.zeros(img.shape) 
merge = other * a 

因此,对于每个标签,我想为 img 和合并找到像素的最小值、像素的最大值和强度的平均值(我可以计算每个标签的面积)。我希望能够用每个标签的这些计数(img 中的连接区域)制作直方图。 (一旦我有了 np 数组或列表,我就知道如何制作直方图了)

我正在考虑为每个标签创建一个循环,然后仅使用该标签创建一个二元结构并测量值。是否有任何快速的 scipy/numpy 方法可以在不经过循环的情况下执行此操作?

谢谢!

请您参考如下方法:

您可以使用 labeled_comprehension 一次性完成所有这些:

#!/usr/bin/env python2.7 
import numpy as np 
from scipy import ndimage as nd 
 
 
hist = [] 
 
def analyze(x): 
    xmin = x.min() 
    xmax = x.max() 
    xmean = x.mean() 
    xhist = np.histogram(x, range=(xmin, xmax)) 
    hist.append({'min': xmin, 
                 'max': xmax, 
                 'mean': xmean, 
                 'hist': xhist}) 
    return 1 
 
a = np.array([[1, 2, 0, 0], 
              [5, 3, 0, 4], 
              [0, 0, 0, 7], 
              [9, 3, 0, 0]]) 
 
lbl, nlbl = nd.label(a) 
 
lbls = np.arange(1, nlbl + 1) 
 
nd.labeled_comprehension(a, lbl, lbls, analyze, float, -1) 
 
print a 
print 
print lbl 
print 
print hist