這是很容易與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