Binarization of grayscale images using the Otsu algorithm
Converting grayscale images to binary images using Otsu's method is useful when you have only two classes in an input image and want to extract them without any manual threshold adjusting. In this recipe, you will learn how to do it.
Getting ready
Before you proceed with this recipe, you will need to install the OpenCV 3.x Python API package and the matplotlib
package.
How to do it...
To complete this recipe, we need to perform the following steps:
- Import the modules:
import cv2 import numpy as np import matplotlib.pyplot as plt
- Read the test image:
image = cv2.imread('../data/Lena.png', 0)
- 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)
- 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...