我有一个二维 numpy 数组,其中有些值为零,有些则不是。我试图找到一种有效的方法来找到数组中最大的零 block (通过返回零的数量,以及中心位置的粗略概念)
例如,在这个数组中,我想找到中心为 (3,4) 的 9 团:
[[ 1, 1, 1, 0, 0 ],
[ 1, 0, 1, 1, 0 ],
[ 1, 1, 1, 1, 1 ],
[ 1, 1, 0, 0, 0 ],
[ 1, 1, 0, 0, 0 ],
[ 1, 1, 0, 0, 0 ]]
在 numpy 或 scipy 中是否有一种很好的矢量化方法来完成这样的事情?
团 block 大致呈圆形,并且没有孔。
ndimage.label() from scipy 做了一些接近于此的事情,但并不是我所追求的。我有一种感觉numpy.where()和 numpy.diff()可能会有帮助,但不确定如何有效地使用它们来解决这个问题。
最佳答案
你就快完成了,你只需要将 ndimage.label
与 numpy.bincount
结合起来:
import numpy as np
from scipy import ndimage
array = np.random.randint(0, 3, size=(200, 200))
label, num_label = ndimage.label(array == 0)
size = np.bincount(label.ravel())
biggest_label = size[1:].argmax() + 1
clump_mask = label == biggest_label
一旦有了 clump_mask
,您就可以计算质心或使用其他方法获得中心。
关于Python - 在 2D numpy 数组中查找特定值的最大面积的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20110232/