确定numpy数组中的相邻区域 [英] Determine adjacent regions in numpy array

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

问题描述

我正在寻找以下内容.我有一个标记为区域的numpy数组. numpy数组表示分割的图像.区域是具有相同值的多个相邻像元.每个地区都有其独特的价值.具有3个区域的简化版本如下所示:

I am looking for the following. I have a numpy array which is labeled as regions. The numpy array represents a segmented image. A region is a number of adjacent cells with the same value. Each region has its own unique value. A simplified version with 3 regions would look like this:

x = np.array([[1, 1, 1], [1, 1, 2], [2, 2, 2], [3, 3, 3]], np.int32)

输出:

array([[1, 1, 1],
       [1, 1, 2],
       [2, 2, 2],
       [3, 3, 3]])

在上面的示例中,我们有3个单独的区域,每个区域都标有唯一值(在这种情况下为1,2,3).

In the above example we have 3 separate regions, each labeled with an unique value (1,2,3 in this case).

我想要的是每个单独区域的相邻(相邻)区域的值.因此,在这种情况下:

What I want is the value of adjacent (neighbor) regions for each individual region. So in this case:

  • 区域1与区域2相邻
  • 第2区与第1区和第3区相邻
  • 第3区与第2区相邻

实现这一目标的最优雅,最快的方法是什么?

What would be the most elegant and fastest way of achieving this?

非常感谢!

推荐答案

我了解任务是返回与给定数字(例如2)相邻的数组的所有不同条目.使用NumPy方法实现此目的的一种方法是使用滚动将给定区域向上,向下,向左和向右移动一个单位.进行移位区域的逻辑或运算,并返回与该条件匹配的所有不同元素.然后,由于不将其视为自己的邻居,因此仍然需要删除该地区本身.

I understand that the task is to return all distinct entries of the array that are adjacent to a given number (such as 2). One way to achieve this with NumPy methods is to use roll to shift the given region by one unit up, down, left, and right. The logical OR of the shifted regions is taken, and all distinct elements that match this condition are returned. It then remains to remove the region itself, since it's not considered its own neighbor.

由于roll重新引入了超出两端两端数组界限的值(此处不希望这样做),因此另一步骤是用False替换此行或列.

Since roll re-introduces the values that move beyond array's bounds at the opposite ends (which is not desired here), an additional step is to replace this row or column with False.

import numpy as np

x = np.array([[1, 1, 1], [1, 1, 2], [2, 2, 2], [3, 3, 3]], np.int32)
region = 2   # number of region whose neighbors we want

y = x == region  # convert to Boolean

rolled = np.roll(y, 1, axis=0)          # shift down
rolled[0, :] = False             
z = np.logical_or(y, rolled)

rolled = np.roll(y, -1, axis=0)         # shift up 
rolled[-1, :] = False
z = np.logical_or(z, rolled)

rolled = np.roll(y, 1, axis=1)          # shift right
rolled[:, 0] = False
z = np.logical_or(z, rolled)

rolled = np.roll(y, -1, axis=1)         # shift left
rolled[:, -1] = False
z = np.logical_or(z, rolled)

neighbors = set(np.unique(np.extract(z, x))) - set([region])
print(neighbors)

这篇关于确定numpy数组中的相邻区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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