How to do it...

  1. Import the modules:
import cv2import numpy as npimport matplotlib.pyplot as plt
  1. Load the test binary image:
image = cv2.imread('../data/BnW.png', 0)
  1. Find the external and internal contours. Organize them into a two-level hierarchy:
_, contours, hierarchy = cv2.findContours(image, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
  1. Prepare the external contour binary mask:
image_external = np.zeros(image.shape, image.dtype)for i in range(len(contours)):    if hierarchy[0][i][3] == -1:        cv2.drawContours(image_external, contours, i,         255, -1)
  1. Prepare the internal contour binary mask:
image_internal = np.zeros(image.shape, image.dtype)for i in range(len(contours)):    if hierarchy[0][i][3] != -1: cv2.drawContours(image_internal, contours, ...

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.