How it works...

There are two functions in OpenCV that can be used to find connected components: cv2.connectedComponents and cv2.connectedComponentsWithStats. Both take the same arguments: the binary image whose components are to be found, the connectivity type, and the depth of the output image, with labels for components. Return values will vary.

cv2.connectedComponents is simpler, and returns a tuple of component numbers and an image with labels for components (labelmap). In addition to the previous function's outputs, cv2.connectedComponentsWithStats also returns statistics about each component and the components' centroid locations.

The labelmap has the same size as the input image, and each of its pixels has a value in the range [0, ...

Get OpenCV 3 Computer Vision with Python Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.