python - 计算numpy数组中的相邻单元格

标签 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

如果值的结构不同,我如何以这种方式计算零的数量? 我不知何故相信必须使用 binary_dilation SciPy 的函数,它能够扩大值(value)结构,但简单的重叠计数不能使我得到正确的总和,还是这样?

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

最佳答案

使用卷积计算邻居数:

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 个相邻值的总和(其他内核也是可能的,例如仅用于正交相邻值的 + 内核).使用这些求和值,我们屏蔽掉原始输入中的零(因为我们不关心它们的邻居),并对整个数组求和。

关于python - 计算numpy数组中的相邻单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12612663/

相关文章:

python - 列值替换

python - 更改音频数据时出现噪音

python - 为什么 random.sample 不能处理 numpy 数组,而 random.choices 可以?

numpy - 使用 numpy 进行 numba 编译有什么问题?

javascript - Facebook 使用收件人数组向多个 friend 发送对话框

javascript - 使用包含属性键和值的字符串创建数组

python - 在 Python 中解压包含 bool 值的结构

python - 如何从 InlineFormset 中的图像字段获取图像 URL?

python - 如何计算scipy中曲线拟合的可能性?

C - 为 char 类型数组分配内存