我有一个表示图像的2D布尔型numpy数组,在其上我调用skimage.measure.label来标记每个分割的区域,从而给我一个int [0,500]的2D数组;此数组中的每个值代表该像素的区域标签。我现在想删除最小的区域。例如,如果我的输入数组是形状(n,n),我希望所有

0, 0, 0, 0, 0, 0, 0, 1, 1, 1
0, 0, 0, 0, 0, 0, 0, 1, 1, 1
0, 0, 7, 8, 0, 0, 0, 1, 1, 1
0, 0, 0, 0, 0, 0, 0, 1, 1, 1
0, 0, 0, 0, 0, 2, 2, 2, 1, 1
4, 4, 4, 4, 2, 2, 2, 2, 1, 1
4, 6, 6, 4, 2, 2, 2, 3, 3, 3
4, 6, 6, 4, 5, 5, 5, 3, 3, 5
4, 4, 4, 4, 5, 5, 5, 5, 5, 5
4, 4, 4, 4, 5, 5, 5, 5, 5, 5


然后输出是

0, 0, 0, 0, 0, 0, 0, 1, 1, 1
0, 0, 0, 0, 0, 0, 0, 1, 1, 1
0, 0, 0, 0, 0, 0, 0, 1, 1, 1  # 7 and 8 are replaced by 0
0, 0, 0, 0, 0, 0, 0, 1, 1, 1
0, 0, 0, 0, 0, 2, 2, 2, 1, 1
4, 4, 4, 4, 2, 2, 2, 2, 1, 1
4, 4, 4, 4, 2, 2, 2, 3, 3, 3  # 6 is gone, but 3 remains
4, 4, 4, 4, 5, 5, 5, 3, 3, 5
4, 4, 4, 4, 5, 5, 5, 5, 5, 5
4, 4, 4, 4, 5, 5, 5, 5, 5, 5


我研究了skimage形态学操作,包括binary closing,但似乎没有一个适用于我的用例。有什么建议么?

最佳答案

您可以通过对与每个标签相对应的布尔区域执行二进制膨胀来实现。通过这样做,您将找到每个区域的邻居数量。然后,您可以使用此值替换所需的值。

有关示例代码:

import numpy as np
import scipy.ndimage

m = 5

arr = [[0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
       [0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
       [0, 0, 7, 8, 0, 0, 0, 1, 1, 1],
       [0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
       [0, 0, 0, 0, 0, 2, 2, 2, 1, 1],
       [4, 4, 4, 4, 2, 2, 2, 2, 1, 1],
       [4, 6, 6, 4, 2, 2, 2, 3, 3, 3],
       [4, 6, 6, 4, 5, 5, 5, 3, 3, 5],
       [4, 4, 4, 4, 5, 5, 5, 5, 5, 5],
       [4, 4, 4, 4, 5, 5, 5, 5, 5, 5]]
arr = np.array(arr)
nval = np.max(arr) + 1

# Compute number of occurances of each number
counts, _ = np.histogram(arr, bins=range(nval + 1))

# Compute the set of neighbours for each number via binary dilation
c = np.array([scipy.ndimage.morphology.binary_dilation(arr == i)
              for i in range(nval)])

# Loop over the set of arrays with bad count and update them to the most common
# neighbour
for i in filter(lambda i: counts[i] < m, range(nval)):
    arr[arr == i] = np.argmax(np.sum(c[:, arr == i], axis=1))


得到预期的结果:

>>> arr.tolist()
[[0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
 [0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
 [0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
 [0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
 [0, 0, 0, 0, 0, 2, 2, 2, 1, 1],
 [4, 4, 4, 4, 2, 2, 2, 2, 1, 1],
 [4, 4, 4, 4, 2, 2, 2, 3, 3, 3],
 [4, 4, 4, 4, 5, 5, 5, 3, 3, 5],
 [4, 4, 4, 4, 5, 5, 5, 5, 5, 5],
 [4, 4, 4, 4, 5, 5, 5, 5, 5, 5]]

关于python - Python numpy数组-最小的区域,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46043048/

10-17 00:28