Skip to content
Advertisement

Getting the coordinates of elements in clusters without a loop in numpy

I have a 2D array, where I label clusters using the ndimage.label() function like this:

JavaScript

I can get the element counts, the centroids or the bounding box of the labeled clusters. But I would like to also get the coordinates of each element in clusters. Something like this (the data structure doesn’t have to be like this, any data structure is okay):

JavaScript

I can loop over the label list and call np.where() for each one of them but I wonder if there is a way to do this without a loop, so that it would be faster?

Advertisement

Answer

You can make a map of the coordinates, sort and split it:

JavaScript
Advertisement