python - numpy 二维数组 : get indices of all entries that are connected and share the same value

标签 python arrays numpy indices

我有一个 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

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

最佳答案

您可以使用 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).

关于python - numpy 二维数组 : get indices of all entries that are connected and share the same value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49771746/

相关文章:

Python tkinter 仅修改具有焦点的列表框

python - 弃用警告 : Function when moving app (removed titlebar) - PySide6

arrays - 在 swift 中使用 alamofire 发送 JSON 数组作为参数

arrays - 将数组拆分为数量相等的容器

python - 替换n维numpy数组中特定轴索引的元素

python - Pandas 分位数功能非常慢

python - 在 Python 中随时间动画线图

Python 不可变类型 ids 和 is 语句

arrays - 如何在 Swift 中获取 2 数组的公共(public)元素列表?

javascript - 为什么 reducer 会忽略数组中的第一项?