简体   繁体   中英

How to count white pixels in every blob in opencv?

I'm looking for a simple and elegant way to count white pixels in every blob individually. For example I have picture like this:

黑白图像

Code:

cv2.findContours(mat.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
areas = [(lambda c: cv2.moments(c)['m00'])(c) for c in contours]

returns [255.0, 482.5, 6480.5, 6230.0, 15531.0, 19810.0], but I want to have just 3 values as there are 3 separate blobs.

The best option seems to be using connectedComponentsWithStats from OpenCV 3.0.

Example:

# find all blobs and label them
n, labels, stats, _ = cv2.connectedComponentsWithStats(mat)
  • n - number of different blobs
  • labels - matrix with the same shape like mat and contains label for every point
  • stats - statistics for every blob in following order:
    • CC_STAT_LEFT The leftmost (x) coordinate which is the inclusive start of the bounding box in the horizontal direction.
    • CC_STAT_TOP The topmost (y) coordinate which is the inclusive start of the bounding box in the vertical direction.
    • CC_STAT_WIDTH The horizontal size of the bounding box
    • CC_STAT_HEIGHT The vertical size of the bounding box
    • CC_STAT_AREA The total area (in pixels) of the connected component

So if you want to know how many pixels are in given blob, just check the row equals to label and fifth column.

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