简体   繁体   中英

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? 在此处输入图片说明

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM