16

I have a large numpy array that I've applied a filter over. I'd like to identify the contiguous regions in this masked array. Here I'm defining a region to be contiguous if, for any index (x1,y1) to any other index (x2,y2), they belong to the same region if there is a path of True values along equal integer steps along the axes (diagonals are valid steps).

That may not be as clear as a simple picture. Given the mask:

0010000
0100000
0110000
0000011
1000010

There should be three regions identified such that the output is something like

[ [[0,2],[1,1],[2,1],[2,2]], [[3,5],[3,6],[4,5]], [[4,0]] ]

I'd like to use something built into numpy, without resorting to writing my own Flood Fill algorithm. A little bit of research in the docs only turned up a 1D version of what I'm asking.

1 Answer 1

26

You're looking for scipy.ndimage.label, more info here. label returns an array the same shape as the input where each "unique feature has a unique value", so if you want the indices of the features you can do something like:

labels, numL = label(array)
label_indices = [(labels == i).nonzero() for i in xrange(1, numL+1)]
Sign up to request clarification or add additional context in comments.

2 Comments

To include diagonals do the following: s = ndimg.generate_binary_structure(2,2) and then labels, numL = ndimg.label(array, structure=s). For a simple and complete explanation, including customisation of the structure beyond diagonals, check: docs.scipy.org/doc/scipy/reference/generated/…
Also, the next step after 'label' could be 'find_objects' of the same package. It returns a list of slices for each found "object". Using start and stop properties of a slice, brings you directly to indices.

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.