Image Thresholding In OpenCV With Example

Fellow coders, in this tutorial we will learn about “Image Thresholding” and implement it with the help of OpenCV in Python. Image thresholding is a technique that is usually performed on a grayscale image. It is a very simple method of image segmentation. There is a fixed constant called threshold value which is compared to every pixel in the image. If the pixel value is less than the threshold then it is set to 0 (black) and if it is greater than the threshold then it is set to 255 (white). We use image thresholding to separate the foreground (object)  from the background and hence it is a segmentation method.

Working with the code:

Now, let us implement simple thresholding with the help of OpenCV. We use OpenCV’s “cv2.threshold” function for this task. We will use the codespeedy logo as the input image. There are different types of thresholding, and we will implement all five of them in the code below:

Input image:
codespeedy logo

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('codespeedy.png')

# converting the image to grascale
logo = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

# saving the image converted image
cv.imwrite('logo_gray.png', logo)

# plotting the histogram of the image

Output image:
gray codespeedy logo

Applying different thresholding:

# different types of thresholding
# we set threshold to 130, you can change it to see what happens!!
ret,thr1 = cv.threshold(logo,130,255,cv.THRESH_BINARY)
ret,thr2 = cv.threshold(logo,130,255,cv.THRESH_BINARY_INV)
ret,thr3 = cv.threshold(logo,130,255,cv.THRESH_TRUNC)
ret,thr4 = cv.threshold(logo,130,255,cv.THRESH_TOZERO)
ret,thr5 = cv.threshold(logo,130,255,cv.THRESH_TOZERO_INV)

cv.imshow('Original Image', logo)
cv.imshow('THRESH_BINARY', thr1) 
cv.imshow('THRESH_BINARY_INV', thr2) 
cv.imshow('THRESH_TRUNC', thr3) 
cv.imshow('THRESH_TOZERO', thr4) 
cv.imshow('THRESH_TOZERO_INV', thr5) 



Leave a Reply

Your email address will not be published. Required fields are marked *