208. Otsu Binarization

Otsu Binarization

Image thresholding is used during the preprocessing phase to binarize images depending on the pixel intensities.
Otsu Binarization is one method to find the appropriate threshold by minimizing the variance between each class.

Here is an implementation example for Otsu binarization using OpenCV. I’ve also added “Global Threshold”(Setting threshold at the center: 127) for comparison.

import cv2
import matplotlib.pyplot as plt

#Read Image
path = '/PATH/TO/Image.jpg'
img = cv2.imread(path)
displaying_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Convert Image to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)

#Apply Global Thresholding
_,gl_th1 = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)

#Apply Otsu Binarization 
_,ots_th = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

fig, axes = plt.subplots(1, 3, figsize=(20,30),facecolor="white")

#Display Output
plt.subplot(1,3,1)
plt.imshow(displaying_img)
plt.title("Original Image")
plt.axis('off')

plt.subplot(1,3,2)
plt.imshow(gl_th1,cmap = "binary")
plt.title("Global Thresholding")
plt.axis('off')

plt.subplot(1,3,3)
plt.imshow(ots_th,cmap = "binary")
plt.title("Otsu Binarization")
plt.axis('off')