【发布时间】:2012-09-18 17:23:09
【问题描述】:
午夜过后,也许有人知道如何解决我的问题。我想计算相邻单元格的数量(这意味着具有其他值的数组字段的数量,例如数组值附近的零)作为每个有效值的总和!。
例子:
import numpy, scipy
s = ndimage.generate_binary_structure(2,2) # Structure can vary
a = numpy.zeros((6,6), dtype=numpy.int) # Example array
a[2:4, 2:4] = 1;a[2,4] = 1 # with example value structure
print a
>[[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 1 1 1 0]
[0 0 1 1 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]]
# The value at position [2,4] is surrounded by 6 zeros, while the one at
# position [2,2] has 5 zeros in the vicinity if 's' is the assumed binary structure.
# Total sum of surrounding zeroes is therefore sum(5+4+6+4+5) == 24
如果我的值的结构不同,我如何以这种方式计算零的数量? 我不知何故认为必须使用 SciPy 的 binary_dilation 函数,它能够扩大值结构,但简单的重叠计数不能让我得到正确的总和,还是这样吗?
print ndimage.binary_dilation(a,s).astype(a.dtype)
[[0 0 0 0 0 0]
[0 1 1 1 1 1]
[0 1 1 1 1 1]
[0 1 1 1 1 1]
[0 1 1 1 1 0]
[0 0 0 0 0 0]]
【问题讨论】:
-
我不完全清楚你想要什么。所以给定一个位置,你想知道值 == 0 的邻居的数量吗?如果您知道数组的形状(查找边缘),您可以使用简单的数学运算……烦人、耗时(编写和处理),但非常简单。