What is an efficient way of counting groups of ones on 2D grid in python? [Figures below]
Question:
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)
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)
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)
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.)
Answers:
scipy.ndimage.measurements.label
does what you need.
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)
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)
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)
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.)
scipy.ndimage.measurements.label
does what you need.