mDumple
mDumple

Reputation: 45

Get the size of each white object in an image python opencv

I am trying to get the size of each separate object in this image so that I can separate them by size. My aim is to be able to loop through them and separate them by size. I have looked everywhere and can't really find anything anywhere. I have tried connected component analysis but I am unsure of how to retrieve size values from it.

_, lab = cv2.connectedComponents(img)

picture

Upvotes: 0

Views: 1917

Answers (1)

Rayees
Rayees

Reputation: 111

Use connectedComponentsWithStats.

# Choose 4 or 8 for connectivity type
connectivity = 4  
output = cv2.connectedComponentsWithStats(img, connectivity, cv2.CV_32S)

num_labels = output[0]
stats = output[2]

for label in range(1,num_labels):
    blob_area = stats[label, cv2.CC_STAT_AREA]
    blob_width = stats[label, cv2.CC_STAT_WIDTH]
    blob_height = stats[label, cv2.CC_STAT_HEIGHT]

num_labels will give the total number of labels. You can use stats matrix to retrieve size of each blob by iterating through each label.

Upvotes: 3

Related Questions