【问题标题】:Counting of adjacent cells in a numpy array计算numpy数组中的相邻单元格
【发布时间】: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 的邻居的数量吗?如果您知道数组的形状(查找边缘),您可以使用简单的数学运算……烦人、耗时(编写和处理),但非常简单。

标签: python arrays numpy scipy


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

【讨论】:

  • 我正要发布几乎相同的答案:(a * ndimage.convolve((a == 0).astype(int), s)).sum()
  • 是的,这正是我想要的。太好了!
【解决方案2】:

我想你已经明白了。膨胀后,1 的数量是 19,减去 5 的起始形状,你有 14。这是围绕你的形状的零的数量。您总共有 24 个重叠。

【讨论】:

  • 这不是正确的答案。考虑一个被 8 个零包围的 1。正确答案是 8,但您会在输出中看到 9 个 1,而您的方法将 添加 1 得到 10。
  • 哦,对不起。您正在计算周围的零没有重叠。我认为海报想要重叠。但您的解决方案适用于无重叠计数。
猜你喜欢
  • 1970-01-01
  • 2016-07-21
  • 2023-03-16
  • 1970-01-01
  • 2019-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多