I am trying this code but it does not return total count for zero[x][y], in this case it should return 5 but all it displays 255 five time.
THIS CODE IS FOR CONNECTED COMPONENTS AND ZERO IS ONE COMPONENT FOR WHITE PIXEL
Expected Output should be:5
But what i am getting is:
255
255
255
255
255
for (x, y) in labels:component = uf.find(labels[(x, y)])# Update the labels with correct informationlabels[(x, y)] = componentpath='imagesNew/13/'if labels[(x, y)]==0:Zero[y][x]=int(255)Z=Zero[y][x]print Zif Z==5:print Zero[y][x]Zeroth = Image.fromarray(Zero)Zeroth.save(path+'Zero'+'.png','png')
I believe this is what you're after. This code will loop through each label in the labeled image, create a boolean mask showing where each label is in the image, and sum that mask to tell you the total count of each label.
import numpy as np
labeled_img = np.array([[1, 1, 0, 0, 2],[1, 0, 0, 2, 2],[1, 0, 2, 2, 2],[1, 1, 1, 2, 2],[1, 1, 1, 2, 2]])for label in np.unique(labeled_img):print('Quantity of', label, 'labels:', np.sum(labeled_img == label))
Quantity of 0 labels: 5
Quantity of 1 labels: 10
Quantity of 2 labels: 10
Note that if you used OpenCV to find the connected components, the first return value of connectedComponents()
is the number of labels, so you can simply loop over for label in range(n_labels)
instead of np.unique()
, which would be a tad faster.