0

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

  • are they always going to be little circles? – user1269942 Dec 10 '19 at 20:05
  • You can use blob detection or connectedcomponents to get the centroids. Or you can use contours, then get the centroids of the contours or get the bounding box around the contours and compute the center of the bounding box. – fmw42 Dec 10 '19 at 21:53

1 Answers1

3

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.stack.imgur.com/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]
Stef
  • 21,187
  • 1
  • 18
  • 46