假设我有这个
import numpy as np
x = np.zeros((10,16), dtype=np.int)
x[6:8,3:11] = 1
x[4:6,5:7] = 1
x[2:4,4:8] = 1
x[4:6,9:11] = 1
x[7,2] = 1
x[6,11] = 1
x[8,3] = 1
print(x)
输出:
[[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 1 1 1 1 0 0 0 0 0 0 0 0]
[0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0]
[0 0 0 0 0 1 1 0 0 1 1 0 0 0 0 0]
[0 0 0 0 0 1 1 0 0 1 1 0 0 0 0 0]
[0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0]
[0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0]
[0 0 0 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]]
我想对其进行过滤,以便删除4个邻域(即上,左,右,下)中少于2个邻居的元素。所以,我最终得到了(将最后三个位置设置为一个):
[[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 1 1 1 1 0 0 0 0 0 0 0 0]
[0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0]
[0 0 0 0 0 1 1 0 0 1 1 0 0 0 0 0]
[0 0 0 0 0 1 1 0 0 1 1 0 0 0 0 0]
[0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0]
[0 0 0 1 1 1 1 1 1 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]]
我尝试使用scipy.ndimage.morphology.binary_closing
,scipy.ndimage.morphology.binary_opening
,scipy.ndimage.morphology.binary_dilation
和scipy.ndimage.morphology.binary_erosion
,但是结果不是我所需要的。我可以进行2个for循环,并遍历数组的每个元素,检查相邻元素,但是我觉得有更好的方法可以做到这一点。我误会了吗?
我对这种特定情况(4个邻域,保留2个邻居)更感兴趣,但是将其推广到另一个邻域或邻居数量(假设二进制数组)容易吗?
答案 0 :(得分:1)
我设法做到了:
from scipy.signal import convolve2d
kernel = [[0,1,0],[1,1,1],[0,1,0]]
filtered = convolve2d(x, kernel, mode='same')
x[filtered<=2] = 0
已过滤:
[[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0]
[0 0 0 1 3 4 4 3 1 0 0 0 0 0 0 0]
[0 0 0 1 3 5 5 3 1 1 1 0 0 0 0 0]
[0 0 0 0 2 4 4 2 1 3 3 1 0 0 0 0]
[0 0 0 1 2 4 4 2 2 4 4 2 0 0 0 0]
[0 0 2 3 4 5 5 4 4 5 5 2 1 0 0 0]
[0 1 2 5 4 4 4 4 4 4 3 2 0 0 0 0]
[0 0 2 2 2 1 1 1 1 1 1 0 0 0 0 0]
[0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0]]
我得到了想要的输出。谢谢@ user3080953