计算numpy数组中相等相邻单元格的数量 [英] Calculate number of equal neighbouring cells within a numpy array

查看:78
本文介绍了计算numpy数组中相等相邻单元格的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有不同大小的二维二进制 numpy arrays,其中包含某些模式.就像这样:

I have 2d binary numpy arrays of varying size, which contain certain patterns. Just like this:

import numpy
a = numpy.zeros((6,6), dtype=numpy.int)
a[1,2] = a[1,3] = 1
a[4,4] = a[5,4] = a[4,3] = 1

这里的图像"包含两个补丁,一个有 2 个,另一个有 3 个连接单元.

Here the "image" contains two patches one with 2 and one with 3 connected cells.

print a
array([[0, 0, 0, 0, 0, 0],
       [0, 0, 1, 1, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 1, 0],
       [0, 0, 0, 0, 1, 0]])


我想知道一个非零单元格与另一个非零单元格(邻居定义为车的情况,因此每个单元格左侧、右侧、下方和上方的单元格)包括它们的伪单元格的频率复制(反之亦然).


I want to know how often a non-zero cell borders another non-zero cell ( neighbours defined as rook's case, so the cells to the left, right, below and above each cell) including their pseudo-replication (so vice-versa).

以前的 方法 返回错误的值 (5),因为它是用于计算外部边界.

A previous approach for inner boundaries returns wrong values (5) as it was intended to calculate outer boundaries.

numpy.abs(numpy.diff(a, axis=1)).sum()

所以对于上面的测试数组,正确的总结果应该是6(上面的补丁有两个内部边界,下面的四个).

So for the above test array, the correct total result would be 6 (The upper patch has two internal borders, the lower four ).

感谢您提供任何提示!

  • 错误:下部显然有 4 个内部边缘(具有相同值的相邻单元格)

  • Mistake: The lower obviously has 4 internal edges (neighbouring cells with the same value)

进一步解释了所需的邻域

Explained the desired neighbourhood a bit more

推荐答案

我认为如果是 8 连通邻域,结果是 8.代码如下:

I think the result is 8 if it's 8-connected neighborhood. Here is the code:

import numpy
a = numpy.zeros((6,6), dtype=numpy.int)
a[1,2] = a[1,3] = 1
a[4,4] = a[5,4] = a[4,3] = 1

from scipy.ndimage import convolve

kernel = np.ones((3, 3))
kernel[1, 1] = 0
b = convolve(a, kernel, mode="constant")
b[a != 0].sum()

但你说的是车的情况.

编辑

这是四连通邻域的代码:

Here is the code for 4-connected neighborhood:

import numpy as np
a = np.zeros((6,6), dtype=np.int)
a[1,2] = a[1,3] = 1
a[4,4] = a[5,4] = a[4,3] = 1

from scipy import ndimage
kernel = ndimage.generate_binary_structure(2, 1)
kernel[1, 1] = 0

b = convolve(a, kernel, mode="constant")
b[a != 0].sum()

这篇关于计算numpy数组中相等相邻单元格的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆