Python OpenCV: Binarize Images Using cv2.adaptiveThreshold()

Binarize images is often used in image processing. In this tutorial, we will introduce how to do using python opencv cv2.adaptiveThreshold().

Python OpenCV - Binarize Images Using cv2.adaptiveThreshold() for beginners

1.Import library

import cv2
import numpy as np
from matplotlib import pyplot as plt

2.Read an image to be grayscale using opencv

image_grey = cv2.imread('images/plane_256x256.jpg', cv2.IMREAD_GRAYSCALE)

Here is a detail tutorial:

Python OpenCV: Read a Color Image to Grayscale Image Using cv2.imread()

2.Binarize image using cv2.adaptiveThreshold()

max_output_value = 255
neighorhood_size = 99
subtract_from_mean = 10
image_binarized = cv2.adaptiveThreshold(image_grey, 
                                        max_output_value, 
                                        cv2.ADAPTIVE_THRESH_GAUSSIAN_C, 
                                        cv2.THRESH_BINARY, 
                                        neighorhood_size, 
                                        subtract_from_mean)

3.Display binarized image

plt.imshow(image_binarized, cmap='gray'), plt.axis("off")
plt.show()

Run this code, you may see binarized image:

Python OpenCV: Binarize Images Using cv2.adaptiveThreshold()