Python – numpy two-dimensional array: get indices of all entries that are connected and share the same value

numpy two-dimensional array: get indices of all entries that are connected and share the same value… here is a solution to the problem.

numpy two-dimensional array: get indices of all entries that are connected and share the same value

I

have a 2D numpy array filled with integer values from 0 to N, how can I get the index of all entries that are directly concatenated and share the same value.

Addendum: Most of the entries are zeros and can be ignored!

Example input array:

[ 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 ]

Desired output metrics:

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

The format of the output array doesn’t matter, I just need a detached cluster of values that can handle a single index

The first thing that comes to my mind is:

N = numberClusters
x = myArray

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

But this misses the separation of clusters with the same value

Solution

You can use > skimage.measure.label (install it using pip install scikit-image if needed) for this:

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)]

You can use a very useful function skimage.measure.regionprops Locate the bounding box, which contains a lot of information about the area. For bounding boxes, it returns a tuple (min_row, min_col, max_row, max_col) where the pixels belonging to the bounding box are in the half-open interval [min_row; max_row) and [min_col; max_col).

Related Problems and Solutions