我在图像上执行了均值漂移分割并获得了标签数组,其中每个点值对应于它所属的分段。
labels = [[0,0,0,0,1],
[2,2,1,1,1],
[0,0,2,2,1]]
另一方面,我有相应的grayScale图像,并希望独立地对每个区域执行操作。
img = [[100,110,105,100,84],
[ 40, 42, 81, 78,83],
[105,103, 45, 52,88]]
让我们说,我想要每个区域的灰度值之和,如果它<200,我想将这些点设置为0(在这种情况下,所有点都在区域2),如何用numpy做到这一点?我确信这比我开始实施的方式更好,其中包括很多很多for循环和临时变量...
答案 0 :(得分:2)
查看numpy.bincount和numpy.where,这应该可以帮到你。例如:
import numpy as np
labels = np.array([[0,0,0,0,1],
[2,2,1,1,1],
[0,0,2,2,1]])
img = np.array([[100,110,105,100,84],
[ 40, 42, 81, 78,83],
[105,103, 45, 52,88]])
# Sum the regions by label:
sums = np.bincount(labels.ravel(), img.ravel())
# Create new image by applying threhold
final = np.where(sums[labels] < 200, -1, img)
print final
# [[100 110 105 100 84]
# [ -1 -1 81 78 83]
# [105 103 -1 -1 88]]
答案 1 :(得分:1)
您正在寻找numpy函数where
。以下是您的入门指示:
import numpy as np
labels = [[0,0,0,0,1],
[2,2,1,1,1],
[0,0,2,2,1]]
img = [[100,110,105,100,84],
[ 40, 42, 81, 78,83],
[105,103, 45, 52,88]]
# to sum pixels with a label 0:
px_sum = np.sum(img[np.where(labels == 0)])