我对图像执行了均值平移分割并获得了标签数组,其中每个点值对应于它所属的片段。
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]]
比方说,我想要每个区域的灰度值之和,如果它<200,我想将这些点设置为0(在这种情况下,区域2中的所有点),我该怎么做与numpy?我确信有比我已经开始的实现更好的方法,其中包括很多很多 for 循环和临时变量...
最佳答案
查看 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]]
关于python - 基于另一个数组中的信息对 NumPy 数组进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30695248/