[SOLVED] Quickly calculating centroid of binary numpy array

Issue

I have a numpy array of 0’s and 1’s (512 x 512). I’d like to calculate the centroid of the shape of 1’s (they’re all connected in one circular blob in the middle of the array).

for i in xrange(len(array[:,0])):
    for j in xrange(len(array[0,:])):
        if array[i,j] == 1:
            x_center += i
            y_center += j

count = (aorta == 1).sum()
x_center /= count
y_center /= count

Is there a way to speed up my calculation above? Could I use numpy.where() or something? Are there any python functions for doing this in parallel?

Solution

You can replace the two nested loops to get the coordinates of the center point, like so –

x_center, y_center = np.argwhere(array==1).sum(0)/count

Answered By – Divakar

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *