How to do it...

In order to execute this recipe, we will perform the following steps:

  1. First, we import all of the modules we need:
import cv2import numpy as np
  1. Open an image and find the connected components in it:
img = cv2.imread('../data/BnW.png', cv2.IMREAD_GRAYSCALE)connectivity = 8num_labels, labelmap = cv2.connectedComponents(img, connectivity, cv2.CV_32S)
  1. Show the original image with the scaled image with labels:
img = np.hstack((img, labelmap.astype(np.float32)/(num_labels - 1)))cv2.imshow('Connected components', img)cv2.waitKey()cv2.destroyAllWindows()
  1. Open another image, find its Otsu mask, and get the connected components with their statistics:
img = cv2.imread('../data/Lena.png', cv2.IMREAD_GRAYSCALE)otsu_thr, otsu_mask ...

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.