Image Thresholding Based on Otsu's Method using OpenCV

Image Thresholding Based on Otsu's Method using OpenCV

Image thresholding is a technique that allows to perform image binarization based on pixel values. Usually, if the pixel value is greater than a threshold, it is set to a maximum value (often 255 - white), otherwise it is set to 0 (black). There are various methods to calculate threshold value. One of them is Otsu's method. It is a global thresholding algorithm, where a single threshold value is applied for the whole image.

OpenCV offers the threshold function to perform image thresholding. We can specify THRESH_OTSU flag as argument to apply Otsu's method to calculate threshold value.

Python
C++
Java
import cv2 img = cv2.imread('test.jpg') grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) thresh, binaryImg = cv2.threshold(grayImg, 0, 255, cv2.THRESH_OTSU) print(thresh) cv2.imshow('Grayscale image', grayImg) cv2.imshow('Binary image', binaryImg) cv2.waitKey(0) cv2.destroyAllWindows()

Calculated threshold value (T) is 155. Result:

Grayscale image converted to binary image using Otsu's method and OpenCV

The 2 Comments Found

    • Avatar
      lindevs Reply

      Hi,
      T=155 refers to a threshold value for an image, which is automatically determined when using Otsu's method.

Leave a Comment

Cancel reply

Your email address will not be published.