首页 > 解决方案 > 如何在 scipy ndimage 中增加标记特征

问题描述

有没有办法在 ndimage 中增加标记特征?理想情况下,通过使用结构来指定增长应该如何发生。我正在使用scipy.ndimage.label()n 维二进制图像中的特征检测,如下所示:

import numpy as np
from scipy import ndimage

a = np.full((8, 8), 1)
a[2, :] = a[5, :] = 0
a[:, 2] = a[:, 5] = 0

print(a)
>>>>
[[1 1 0 1 1 0 1 1]
 [1 1 0 1 1 0 1 1]
 [0 0 0 0 0 0 0 0]
 [1 1 0 1 1 0 1 1]
 [1 1 0 1 1 0 1 1]
 [0 0 0 0 0 0 0 0]
 [1 1 0 1 1 0 1 1]
 [1 1 0 1 1 0 1 1]]

s = [
    [0, 1, 0],
    [1, 1, 1],
    [0, 1, 0],
]

labeled, num = ndimage.label(a, structure=s)

print(labeled)
>>>>
[[1 1 0 2 2 0 3 3]
 [1 1 0 2 2 0 3 3]
 [0 0 0 0 0 0 0 0]
 [4 4 0 5 5 0 6 6]
 [4 4 0 5 5 0 6 6]
 [0 0 0 0 0 0 0 0]
 [7 7 0 8 8 0 9 9]
 [7 7 0 8 8 0 9 9]]

现在假设我想用 label 扩展功能2。这是一些伪代码和输出来说明我想要的结果:

# pseudo code
grown = ndimage.grow(labeled, label=2, structure=s)
print(grown)
[[1 1 2 2 2 2 3 3]
 [1 1 2 2 2 2 3 3]
 [0 0 0 2 2 0 0 0]
 [4 4 0 5 5 0 6 6]
 [4 4 0 5 5 0 6 6]
 [0 0 0 0 0 0 0 0]
 [7 7 0 8 8 0 9 9]
 [7 7 0 8 8 0 9 9]]

任何帮助将不胜感激!似乎 scipy 应该能够完成一些事情,但是我对这个模块还是新手,我在搜索文档以查找我想做的事情时遇到了麻烦。

标签: scipyscipy.ndimage

解决方案


当我首先过滤数组时,我发现它scipy.ndimage.binary_dilation可以满足我的需要:

filtered = np.where(labeled == 2, 1, 0)
grown = ndimage.binary_dilation(filtered, structure=s).astype(np.int)

print(grown)
>>>>
[[0 0 1 1 1 1 0 0]
 [0 0 1 1 1 1 0 0]
 [0 0 0 1 1 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]]

伪代码的输出可以通过梳理grown等来实现labeled

print(np.where(grown, 2, labeled))
>>>>
[[1 1 2 2 2 2 3 3]
 [1 1 2 2 2 2 3 3]
 [0 0 0 2 2 0 0 0]
 [4 4 0 5 5 0 6 6]
 [4 4 0 5 5 0 6 6]
 [0 0 0 0 0 0 0 0]
 [7 7 0 8 8 0 9 9]
 [7 7 0 8 8 0 9 9]]

推荐阅读