1

I wonder if there is a function to group equal, connected elements of a 2D array like

a = np.array([[12,12,14,14,11,11],
              [10,10,11,11,11,11],
              [10,14,14,10,11,13],
              [12,12,14,13,13,13]])

into an array this:

            [[1, 1, 2 ,2, 3, 3],
             [4, 4, 3, 3, 3, 3],
             [4, 5, 5, 6, 3 ,7],
             [8, 8, 5, 7, 7, 7]]

The rules for connection: an element [i, j] is connected to [i-1, j], [i+1, j], [i, j-1], and [i, j+1].

I found scipy.ndimage.measurements.label but the problem is that it just consider the array values as zero (background) and ones.

8
  • What's wrong with the first array? The elements are already "grouped". Commented Nov 28, 2017 at 2:43
  • @ReblochonMasque for example 12,12 in the first row is grouped as 1 but in the last row as 8 Commented Nov 28, 2017 at 2:46
  • 1
    Then why is 10 in the second row in the same group as 10 in the 3rd? Commented Nov 28, 2017 at 2:47
  • this one was a mistake, edited the question. Commented Nov 28, 2017 at 2:49
  • Still a mistake: 2nd row: 10 maps to 4, 3rd row, 10 maps to 4, then maps to 6! Commented Nov 28, 2017 at 2:49

1 Answer 1

2

Depending on the number of unique values, it may be practical to simply use label in a loop, adding the results with appropriate offsets. The offsets are needed because after, say, the first 3 features are labeled, the labels for subsequent ones should begin with 4, and so on.

from scipy.ndimage import label
values = np.unique(a.ravel())
offset = 0
result = np.zeros_like(a)
for v in values:
  labeled, num_features = label(a == v)
  result += labeled + offset*(labeled > 0)
  offset += num_features
print(result)

This prints

[[4 4 7 7 3 3]
 [1 1 3 3 3 3]
 [1 8 8 2 3 6]
 [5 5 8 6 6 6]]

which is the same as your expected result, up to permutation of labels (which don't have any meaning anyway).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.