这是很容易与basic morphological operation:
import numpy as np
from scipy.ndimage.morphology import binary_erosion
data = np.array([[1, 1 , 0 , 0 , 0 , 0 , 1 , 0],
[1, 1 , 1 , 1 , 1 , 1 , 1 , 0],
[1, 1 , 1 , 1 , 1 , 1 , 1 , 0],
[0, 0 , 1 , 1 , 1 , 1 , 1 , 0],
[0, 0 , 1 , 1 , 1 , 1 , 1 , 1],
[1, 1 , 1 , 1 , 1 , 1 , 1 , 0],
[1, 1 , 0 , 0 , 0 , 0 , 0 , 0]])
expected = np.array([[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 , 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]])
# otherwise known as np.ones((5, 5))
structuring_element = np.array([[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]])
# will be of dtype np.bool but you can convert with .astype(np.int)
# if you really need
result = binary_erosion(data, structuring_element)
print(result)
print(np.allclose(result, expected))
感谢您的尝试。我有upvoted。不过,我正在考虑使用scipy.ndimage来做这件事。你能否提出一种替代方法? –
like maximum_filter,minimum_filter? –
@EricBal我不认为max或min过滤器可以在这里工作,但那些过滤器会在该窗口内寻找最大值。我们想要的是该窗口中的所有元素都是“ones”。所以我们需要的是在该窗口内的所有元素的总和,所以卷积适合这里。 – Divakar