scipy.ndimage.label:包括误差范围

2024-10-06 12:09:07 发布

您现在位置:Python中文网/ 问答频道 /正文

在读了一个关于scipy.ndimage.label(Variable area threshold for identifying objects - python),我想在标签中包含一个“误差范围”。在

在上述链接讨论中: 上面的蓝色圆点怎么也包括在内(假设它错误地与橙色最大的对象断开连接)?在

我找到了structure属性,通过改变数组(从np.ones公司(3,3,3)比这更重要(我希望它是3D的)。然而,不幸的是,将“structure”属性调整为更大的数组似乎不起作用。它要么给出维度的错误(RuntimeError:结构和输入必须具有相等的秩 )或者它不会改变任何东西。。在

谢谢!在

代码如下:

labels, nshapes = ndimage.label(a, structure=np.ones((3,3,3)))

其中a是一个3D数组。在


Tags: forthreshold属性objects错误nponesarea
1条回答
网友
1楼 · 发布于 2024-10-06 12:09:07

这里有一个使用^{}的可能方法。在2D示例中更容易看到发生了什么,但最后我将演示如何将其推广到3D。在

In [103]: a
Out[103]: 
array([[0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [1, 1, 0, 0, 1, 0, 0],
       [1, 1, 0, 0, 0, 1, 1],
       [0, 0, 0, 0, 0, 1, 1],
       [1, 1, 1, 0, 0, 0, 0]])

In [104]: from scipy.ndimage import label, binary_dilation

将每个“形状”向下和向右延伸一个像素:

^{pr2}$

label应用于填充数组:

In [107]: labels, numlabels = label(b)

In [108]: numlabels
Out[108]: 2

In [109]: labels
Out[109]: 
array([[0, 0, 0, 1, 1, 0, 0],
       [0, 0, 0, 1, 1, 0, 0],
       [2, 2, 2, 0, 1, 1, 0],
       [2, 2, 2, 0, 1, 1, 1],
       [2, 2, 2, 0, 0, 1, 1],
       [2, 2, 2, 2, 0, 1, 1]], dtype=int32)

通过将a乘以labels,我们得到了a所需的标签数组:

In [110]: alab = labels*a

In [111]: alab
Out[111]: 
array([[0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [2, 2, 0, 0, 1, 0, 0],
       [2, 2, 0, 0, 0, 1, 1],
       [0, 0, 0, 0, 0, 1, 1],
       [2, 2, 2, 0, 0, 0, 0]])

(这假定a中的值为0或1。如果不是,可以使用alab = labels * (a > 0)。)

对于三维输入,必须将structure参数改为binary_dilation

struct = np.zeros((3, 3, 3), dtype=int)
struct[1:, 1:, 1:] = 1
b = binary_dilation(a, structure=struct).astype(int)

相关问题 更多 >