2D numpy的基于阵列检查,看看是否所有相邻方面都是平等的
我开始用n×m个布尔数组,定义regions-真,如果是在该地区,否则为false。例如:
I am starting with a nxm boolean array, that defines regions- true if it is in the region, false if not. For example:
r = np.array([[ 0, 0, 1, 1, 1],
[ 0, 1, 1, 0, 0],
[ 0, 1, 1, 1, 0],
[ 1, 1, 1, 0, 0],
[ 1, 1, 0, 0, 0]])
区域之间的线可以被定义为n 1×m-1个阵列中,这将重新present在每组四个值之间的点。如果所有4个周边值是相同的,你是不是在区域之间的边缘。如果任何的4个值不同,则是。上述R:
The line between regions can be defined as an n-1 x m-1 array, which would represent a 'point' in between each set of four values. If all 4 surrounding values are the same, you are not on the edge between regions. If any of the 4 values are different, you are. For r above:
l = np.array([[ 1, 1, 1, 1],
[ 1, 0, 1, 1],
[ 1, 0, 1, 1],
[ 0, 1, 1, 0]])
这是如何能够高效地完成有什么想法?我曾尝试做两个方向的一个差异,但这双打。是否有一个二维差异函数?这样做的其他方式?
Any thoughts on how this can be done efficiently? I have tried doing a diff in both directions, but this doubles up. Is there a 2D diff function? Some other way of doing this?
这将做的百分点的由真包围测试
,
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]]