Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify contiguous regions in 2D numpy array

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.

like image 770
Hooked Avatar asked Feb 25 '12 03:02

Hooked


1 Answers

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)]
like image 181
Bi Rico Avatar answered Sep 28 '22 00:09

Bi Rico