Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an efficient way of counting groups of ones on 2D grid in python? [Figures below]

I have a few hundred 2D numpy arrays. They contain zeros and ones. A few examples with plots, yellow indicates ones, purple indicates zeros:

grid1=np.array([[1, 1, 0, 0, 1, 1, 0, 0],
               [1, 1, 0, 1, 1, 1, 0, 0],
               [1, 1, 0, 1, 1, 1, 0, 0],
               [1, 0, 0, 0, 1, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0]])

plt.imshow(grid1)

enter image description here

grid2=np.array([[1, 1, 0, 0, 0, 0, 0, 0],
               [1, 1, 1, 1, 1, 0, 0, 0],
               [1, 1, 1, 1, 1, 0, 0, 0],
               [1, 0, 0, 1, 1, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0]])

plt.imshow(grid2)

enter image description here

grid3=np.array([[1, 1, 0, 0, 1, 0, 0, 1],
               [0, 1, 0, 1, 1, 0, 1, 1],
               [0, 1, 0, 1, 1, 0, 0, 0],
               [0, 0, 0, 0, 1, 1, 1, 0],
               [1, 1, 1, 0, 0, 0, 0, 0]])

plt.imshow(grid3)

enter image description here

I'm looking for an efficient way to count the number of yellow blobs on the images. 2, 1 and 4 blobs on the images above, from top to bottom.

Is there an easy way to do this or I have to check each yellow bit to be in the same blob as all the other yellows, and write a script for that? (That looks very painful.)

like image 763
zabop Avatar asked Dec 02 '25 23:12

zabop


1 Answers

scipy.ndimage.measurements.label does what you need.

like image 51
Eelco Hoogendoorn Avatar answered Dec 05 '25 11:12

Eelco Hoogendoorn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!