How to do it...

To complete this recipe, we need to perform the following steps:

  1. Import the modules:
import cv2import numpy as npimport matplotlib.pyplot as plt
  1. Read the test image:
image = cv2.imread('../data/Lena.png', 0)
  1. Estimate the threshold using Otsu's method:
otsu_thr, otsu_mask = cv2.threshold(image, -1, 1, cv2.THRESH_BINARY | cv2.THRESH_OTSU)print('Estimated threshold (Otsu):', otsu_thr)
  1. Visualize the results:
plt.figure()plt.subplot(121)plt.axis('off')plt.title('original')plt.imshow(image, cmap='gray')plt.subplot(122)plt.axis('off')plt.title('Otsu threshold')plt.imshow(otsu_mask, cmap='gray')plt.tight_layout()plt.show()

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.