Scipy标签及每个标签中最大像素的测量

2 投票
1 回答
1764 浏览
提问于 2025-04-18 03:12

我想用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中连接的区域)。
(我知道一旦有了numpy数组或列表,怎么制作直方图)

我在考虑为每个标签做一个循环,然后只用那个标签创建一个二进制结构来测量这些值。有没有什么快速的scipy/numpy方法可以做到这一点,而不需要通过循环?

谢谢!

1 个回答

1

你可以使用 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

撰写回答