How to get pixel locations of all the white blobs

I am creating annotations from binary images. I want the separate lists for each white blob list in the binary image. So following the image I have given below I should get six arrays/lists.

I used np.argwhere(img == 255) following this Numpy + OpenCV-Python : Get coordinates of white pixels but it returns me the combined pixels locations of all the white blobs.

And I have used this cv2.findContours(threshed, cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)[-2] but this returns the pixel values of the outer edge not the entire blob. How can I get separate lists from the image? enter image description here

Upvotes: 1

Views: 1264

Answers (1)

Stef
Stef

Reputation: 30639

You can use connectedComponents:

r,l = cv2.connectedComponents(img)
blobs = [np.argwhere(l==i) for i in range(1,r)]

(label 0 is the background, that's why we start with 1 in range(1,r))

Example:

import cv2
from urllib.request import urlopen
import numpy as np

req = urlopen('https://i.sstatic.net/RcQut.jpg')
arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
img = cv2.imdecode(arr, cv2.IMREAD_GRAYSCALE) 
img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1]

r,l = cv2.connectedComponents(img)

print([len(np.argwhere(l==i)) for i in range(1,r)]) #just the lenghts for shortness
#[317, 317, 377, 797, 709, 613]

Upvotes: 5

Related Questions