MATLAB 的 label2idx 在给定标记图像的情况下输出扁平索引(按列排序)。
我们可以使用scikit-image's 内置regionprops 从标记的图像中获取这些索引。 Scikit-image 还为我们提供了一个内置功能来获取标记的图像,因此使用同一个包即可。实现看起来像这样 -
from skimage.measure import label,regionprops
def label2idx(L):
# Get region-properties for all labels
props = regionprops(L)
# Get XY coordinates/indices for each label
indices = [p.coords for p in props]
# Get flattened-indices for each label, similar to MATLAB version
# Note that this is row-major ordered.
flattened_indices = [np.ravel_multi_index(idx.T,L.shape) for idx in indices]
return indices, flattened_indices
示例运行 -
# Input array
In [62]: a
Out[62]:
array([[1, 1, 1, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 1, 1, 0, 0],
[1, 1, 1, 0, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 1, 0],
[1, 1, 1, 0, 0, 0, 1, 0],
[1, 1, 1, 0, 0, 1, 1, 0],
[1, 1, 1, 0, 0, 0, 0, 0]])
# Get labeled image
In [63]: L = label(a)
In [64]: idx,flat_idx = label2idx(L)
In [65]: flat_idx
Out[65]:
[array([ 0, 1, 2, 8, 9, 10, 16, 17, 18, 24, 25, 26, 32, 33, 34, 40, 41,
42, 48, 49, 50, 56, 57, 58]),
array([12, 13, 20, 21]),
array([38, 46, 53, 54])]
如果您需要像 MATLAB 中那样以列优先顺序排列的索引,只需转置图像,然后输入 -
In [5]: idx,flat_idx = label2idx(L.T)
In [6]: flat_idx
Out[6]:
[array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23]),
array([33, 34, 41, 42]),
array([46, 52, 53, 54])]
请注意,索引仍然从 0 开始,不像在 MATLAB 中它从 1 开始。
使用 SciPy 获取标记图像的替代方法
SciPy 还内置了获取标签图像的功能:scipy.ndimage.label -
from scipy.ndimage import label
L = label(a)[0]