1

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

5

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
  • 28,728
  • 2
  • 24
  • 52
  • what does the result of this even mean? like the printed array .. I am trying to find the coordinates of the white blobs and only if it's a bigger accumulation of blobs – Mika C. Oct 06 '22 at 04:00
  • @MikaC. the example result shows the number of pixels in the components, i.e. the 1st componenent has an area of 317 pixels (i.e. the length of the argwhere array that gives the locations of all the pixels in the given component) – Stef Oct 06 '22 at 06:14