计算numpy数组的周长 [英] Calculate perimeter of numpy array

查看:225
本文介绍了计算numpy数组的周长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算给定numpy数组结构的周长.外围是指numpy数组中结构的确切外围.该结构可能包含孔.

I want to calculate the perimeter of a given numpy array structure. With perimeter i mean the exact perimeter of the structure in the numpy array. The structure could include holes.

我目前的方法是这样的:

My current aproach is something like this:

import numpy   
a = numpy.zeros((6,6), dtype=numpy.int)
a[1:5, 1:5] = 1;a[3,3] = 0
# Way 1
s = ndimage.generate_binary_structure(2,1)
c = ndimage.binary_dilation(a,s).astype(a.dtype)
b = c - a  
numpy.sum(b) # The result, however the hole is calculated as 1, although there are 4 edges

# Way 2
b = ndimage.distance_transform_cdt(a == 0,metric='taxicab') == 1 
b = b.astype(int)
numpy.sum(b) # same as above

如您所见,它将显示所有相邻的单元格,但是它们的总和不等于补丁的周长.尽管示例数组中的孔正确具有4个边,但该孔的计算结果为1.存在具有不同形状的较大孔的类似问题.

As you can see it displays all adjacent cells, however the sum of them doesn't equal the perimeter of the patch. The hole in the example array is calculated as 1 although it correctly has 4 edges. There are similar issues with greater holes of different shapes.

我过去曾问过类似的问题,但所有问题都提供了解决方案,但最终都无法以正确的输出值解决. 有人有一个想法如何做到这一点? 除了numpy,scipy和基本软件包外,没有其他软件包.

I have asked similar questions in the past, but all provided solutions which somehow didn't resolve in the correct output values in the end. Someone has an idea how to accomplish this? No other packages than numpy, scipy and the base packages please.

推荐答案

在图像中,您的意思是将蓝色瓷砖与红色瓷砖分开的长度为1的边的总数吗?在上面的图片中,该数字为28.在您输入的示例代码中(该代码略有不同,四个角与其余边框的差异不大)为20.

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,:])

这篇关于计算numpy数组的周长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆