我有一个二维数组,我在其中使用如下ndimage.label()
函数标记集群:
import numpy as np
from scipy.ndimage import label
input_array = np.array([[0, 1, 1, 0],
[1, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 0, 1]])
labeled_array, _ = label(input_array)
# Result:
# labeled_array == [[0, 1, 1, 0],
# [1, 1, 0, 0],
# [0, 0, 0, 2],
# [0, 0, 0, 2]]
我可以获得元素计数、质心或标记簇的边界框。但我也想获得集群中每个元素的坐标。像这样的东西(数据结构不必是这样的,任何数据结构都可以):
{
1: [(0, 1), (0, 2), (1, 0), (1, 1)], # Coordinates of the elements that have the label "1"
2: [(2, 3), (3, 3)] # Coordinates of the elements that have the label "2"
}
我可以遍历标签列表并调用np.where()
它们中的每一个,但我想知道是否有一种方法可以在没有循环的情况下执行此操作,这样它会更快?