Finding external and internal contours in a binary image
Having contours extracted from a binary image gives you an alternative image representation and allows you to apply contour-specific image analysis methods. In this recipe, you will learn how to find contours in a binary image.
Getting ready
For this recipe, ensure that you have installed the OpenCV 3.x Python API package and the matplotlib package.
How to do it...
- Import the modules:
import cv2 import numpy as np import matplotlib.pyplot as plt
- Load the test binary image:
image = cv2.imread('../data/BnW.png', 0)- 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)
- 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)- Prepare the internal contour binary...