小编典典

numpy数组中相邻单元的计数

python

午夜过后,也许有人知道如何解决我的问题。我想将相邻单元格的数量(这意味着具有其他值的数组字段的数量,例如数组值附近的零)作为 每个有效值的 总和

例:

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]]

阅读 267

收藏
2021-01-20

共1个答案

小编典典

使用 卷积 计算邻居数:

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)

b = 1-a 允许我们计算每个零而忽略它们。

我们使用一个3x3全为内核,将每个元素设置为其元素与它的8个相邻值的和(其他内核也是可能的,例如+仅正交相邻值的内核)。使用这些求和的值,我们屏蔽了原始输入中的零(因为我们不在乎它们的邻居),并对整个数组求和。

2021-01-20