Cur*_*lew 4 python arrays numpy scipy
过了午夜,也许有人知道如何解决我的问题.我想计算相邻单元格的数量(这意味着具有其他值的数组字段的数量,例如,在数组值附近的零)作为每个有效值的总和!.
例:
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
Run Code Online (Sandbox Code Playgroud)
如果我的值的结构变化,我怎么能以这种方式计算零的数量?我不知怎的相信必须使用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]]
Run Code Online (Sandbox Code Playgroud)
使用卷积来计算邻居:
import numpy
import scipy.signal
a = numpy.zeros((6,6), dtype=numpy.int) # Example array
a[2:4, 2:4] = 1;a[2,4] = 1 # with example value structure
b = 1-a
c = scipy.signal.convolve2d(b, numpy.ones((3,3)), mode='same')
print numpy.sum(c * a)
Run Code Online (Sandbox Code Playgroud)
b = 1-a 允许我们计算每个零而忽略那些零.
我们使用3x3 all-one内核进行卷积,该内核将每个元素设置为它的总和及其8个相邻值(其他内核是可能的,例如+内核仅用于正交相邻的值).使用这些求和值,我们屏蔽原始输入中的零(因为我们不关心它们的邻居),并对整个数组求和.
| 归档时间: |
|
| 查看次数: |
3226 次 |
| 最近记录: |