2D numpy array- check to see if all adjacent terms are equal

故事扮演 提交于 2019-12-04 15:50:54

This will do the test for points surrounded by True,

tmp = r[1:] & r[:-1]
l = np.logical_not(tmp[:, 1:] & tmp[:, :-1])

Then you can do the test for points surrounded by False the same way and combine them,

r = np.logical_not(r)
tmp = r[1:] & r[:-1]
l &= np.logical_not(tmp[:, 1:] & tmp[:, :-1])

print l.astype(int)
# [[1 1 1 1]
#  [1 0 1 1]
#  [1 0 1 1]
#  [0 1 1 0]]

An good answer's already selected, but I like solutions that are easy to write and understand so I'll still post this:

from scipy.signal import convolve2d
kernel = np.array(((1, 1), (1, 1)))

x = convolve2d(r, kernel, mode="valid")   # sum all the neighboring values (and mode handles the boundary issues)
x[x==4] = 0                               # set the elements that sum to 4 to zero (the ones that sum to 0 are already 0)
x[x>0] = 1                                # anything greater than one is set to 1

[[1 1 1 1]
 [1 0 1 1]
 [1 0 1 1]
 [0 1 1 0]]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!