Calculate perimeter of numpy array

拜拜、爱过 提交于 2019-11-30 14:34:12

Do you mean, in the image, the total number of length-1 edges that separate blue-colored from red-colored tiles? In the picture above this number would be 28. In the example you give in code (which is slightly different, not having the 4 corners differ from the rest of the border tiles) it would be 20.

If that's what you want to compute, you can do something like:

numpy.sum(a[:,1:] != a[:,:-1]) + numpy.sum(a[1:,:] != a[:-1,:])

Count the number of edges in the interior and at the edges (assumes binary image):

n_interior = abs(diff(a, axis=0)).sum() + abs(diff(a, axis=1)).sum()
n_boundary = a[0,:].sum() + a[:,0].sum() + a[-1,:].sum() + a[:,-1].sum()
perimeter = n_interior + n_boundary

You can leave out n_boundary if the image is properly zero padded.

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