【问题标题】:numpy 2D array: get indices of all entries that are connected and share the same valuenumpy 2D array:获取所有连接并共享相同值的条目的索引
【发布时间】:2018-09-21 03:25:12
【问题描述】:

我有一个 2D numpy 数组,其中填充了从 0 到 N 的整数值,我如何获取所有直接连接并共享相同值的条目的索引。

补充:大部分条目都是零,可以忽略!

示例输入数组:

[ 0 0 0 0 0 ]
[ 1 1 0 1 1 ]
[ 0 1 0 1 1 ]
[ 1 0 0 0 0 ]
[ 2 2 2 2 2 ]

希望的输出指数:

1: [ [1 0] [1 1] [2 1] [3 0] ] # first 1 cluster
   [ [1 3] [1 4] [2 3] [2 4] ] # second 1 cluster

2: [ [4 0] [4 1] [4 2] [4 3] [4 4] ] # only 2 cluster

输出数组的格式并不重要,我只需要可以处理单个索引的分离值簇

我首先想到的是:

N = numberClusters
x = myArray

for c in range(N):
   for i in np.where(x==c):
         # fill output array with i

但这错过了具有相同值的集群的分离

【问题讨论】:

  • 连接意味着'在同一行'?
  • 连接的意思是它们在 x,y 或对角坐标中“接触”对方。看看我是如何对“那些”进行聚类的例子,我希望这能说清楚。
  • 寻找connected components labeling algorithm实现

标签: python arrays numpy indices


【解决方案1】:

您可以为此使用skimage.measure.label(如果需要,请使用pip install scikit-image 安装它):

import numpy as np
from skimage import measure

# Setup some data
np.random.seed(42)
img = np.random.choice([0, 1, 2], (5, 5), [0.7, 0.2, 0.1])
# [[2 0 2 2 0]
#  [0 2 1 2 2]
#  [2 2 0 2 1]
#  [0 1 1 1 1]
#  [0 0 1 1 0]]

# Label each region, considering only directly adjacent pixels connected
img_labeled = measure.label(img, connectivity=1)
# [[1 0 2 2 0]
#  [0 3 4 2 2]
#  [3 3 0 2 5]
#  [0 5 5 5 5]
#  [0 0 5 5 0]]

# Get the indices for each region, excluding zeros
idx = [np.where(img_labeled == label)
       for label in np.unique(img_labeled)
       if label]
# [(array([0]), array([0])),
#  (array([0, 0, 1, 1, 2]), array([2, 3, 3, 4, 3])),
#  (array([1, 2, 2]), array([1, 0, 1])),
#  (array([1]), array([2])),
#  (array([2, 3, 3, 3, 3, 4, 4]), array([4, 1, 2, 3, 4, 2, 3]))]

# Get the bounding boxes of each region (ignoring zeros)
bboxes = [area.bbox for area in measure.regionprops(img_labeled)]
# [(0, 0, 1, 1),
#  (0, 2, 3, 5),
#  (1, 0, 3, 2),
#  (1, 2, 2, 3),
#  (2, 1, 5, 5)]

可以使用非常有用的函数skimage.measure.regionprops 找到边界框,其中包含有关区域的大量信息。对于边界框,它返回一个元组(min_row, min_col, max_row, max_col),其中属于边界框的像素位于[min_row; max_row)[min_col; max_col) 的半开区间内。

【讨论】:

  • 我怎样才能另外获得分配给边界框的类?因为当我选择分配给框坐标的类时,我大多会得到背景,因为 x,y 最小值最大值通常不位于对象上
  • @GustavZ 哪个标签?原始数组中的值?您可以为此使用[img[i][0] for i in idx]。如果你想要标签给出的标签,你可以使用[area.label for area in measure.regionprops(img_labeled)]
  • 是的,正是[img[i][0] for i in idx] 所做的,但这只是给了我当前图像中的所有标签(如分类),但我想为我计算的每个边界框找到确切的标签与boxes = [area.bbox for area in measure.regionprops(map_labeled)](如检测)我该怎么做?因为现在我只是假设盒子中间应该是对象,我拿了那个标签......
  • @GustavZ 见我上面的评论:[area.label for area in measure.regionprops(img_labeled)].
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-04
  • 1970-01-01
  • 2017-08-09
  • 1970-01-01
  • 2013-09-26
  • 1970-01-01
  • 2017-09-21
相关资源
最近更新 更多