dragon7
dragon7

Reputation: 1133

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:

black and white image

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.

Upvotes: 3

Views: 2701

Answers (1)

dragon7
dragon7

Reputation: 1133

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.

Upvotes: 2

Related Questions