Instagram
youtube
Facebook
Twitter

Thresholding Images

Thresholding is a method in image processing used to convert a grayscale or colored image into a binary image (black and white) based on a threshold value. In OpenCV, there are several types of thresholding methods available like - Binary Thresholding, Adaptive Thresholding, Binary Inverse Thresholding and Truncated Thresholding, etc. In this tutorial, we’ll learn about image thresholding using OpenCV.

what is cv2.threshold() function?

It is a function in OpenCV for thresholding images. It takes some parameters like - input image, the threshold value, the maximum value to use in the thresholded image, and the thresholding type as arguments.

Let's understand the concept with some practical work.

1. binary thresholding:
In this type of thresholding all pixels above a threshold value are set to a maximum value and all pixels below the threshold value are set to zero.

Input

Code:

import cv2
img = cv2.imread('opencv8.jpg')  
ret, image = cv2.threshold(img, 50,50,  cv2.THRESH_BINARY)
cv2.imshow('Bilateral filtered Image', image)
cv2.imwrite('binaryth.jpg', image)
cv2.waitKey(0)  
cv2.destroyAllWindows()

Here, first, we imported cv2 and used cv2.imread to read the image. Then, we used cv2.threshold to threshold the input image with 50 threshold value and 50 maximum value.

Result:

 2. Binary inverse thresholding:

In this type of thresholding all pixels below the threshold value are set to the maximum value and all pixels above the threshold value are set to zero.

Input

Code:

import cv2
img = cv2.imread('opencv8.jpg')  
ret, image = cv2.threshold(img, 50,200,  cv2.THRESH_BINARY_INV)
cv2.imshow('Image', image)
cv2.waitKey(0)  
cv2.destroyAllWindows()

Here, we have used binary inverse thresholding

Result:

  3. Truncated Thresholding

In this type of thresholding all pixels above a specified threshold value to the threshold value, while all pixels below the threshold value remain unchanged

Input

Code:

import cv2
img = cv2.imread('opencv8.jpg')  
ret, image = cv2.threshold(img, 50,200,  cv2.THRESH_BINARY_INV)
cv2.imshow('Image', image)
cv2.waitKey(0)  
cv2.destroyAllWindows()

Here, we have used binary inverse thresholding

Result: