Python | Thresholding techniques using OpenCV | Set1 (Simple Thresholding) (original) (raw)

Last Updated : 04 Jan, 2023

Thresholding is a technique in OpenCV, which is the assignment of pixel values in relation to the threshold value provided. In thresholding, each pixel value is compared with the threshold value. If the pixel value is smaller than the threshold, it is set to 0, otherwise, it is set to a maximum value (generally 255). Thresholding is a very popular segmentation technique, used for separating an object considered as a foreground from its background. A threshold is a value which has two regions on its either side i.e. below the threshold or above the threshold.
In Computer Vision, this technique of thresholding is done on grayscale images. So initially, the image has to be converted in grayscale color space.

If f (x, y) < T then f (x, y) = 0 else f (x, y) = 255

where f (x, y) = Coordinate Pixel Value T = Threshold Value.

In OpenCV with Python, the function cv2.threshold is used for thresholding.

Syntax: cv2.threshold(source, thresholdValue, maxVal, thresholdingTechnique)
Parameters:
-> source: Input Image array (must be in Grayscale).
-> thresholdValue: Value of Threshold below and above which pixel values will change accordingly.
-> maxVal: Maximum value that can be assigned to a pixel.
-> thresholdingTechnique: The type of thresholding to be applied.

Simple Thresholding

The basic Thresholding technique is Binary Thresholding. For every pixel, the same threshold value is applied. If the pixel value is smaller than the threshold, it is set to 0, otherwise, it is set to a maximum value.
The different Simple Thresholding Techniques are:

Below is the Python code explaining different Simple Thresholding Techniques –

Python3

import cv2

import numpy as np

image1 = cv2.imread( 'input1.jpg' )

img = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)

ret, thresh1 = cv2.threshold(img, 120 , 255 , cv2.THRESH_BINARY)

ret, thresh2 = cv2.threshold(img, 120 , 255 , cv2.THRESH_BINARY_INV)

ret, thresh3 = cv2.threshold(img, 120 , 255 , cv2.THRESH_TRUNC)

ret, thresh4 = cv2.threshold(img, 120 , 255 , cv2.THRESH_TOZERO)

ret, thresh5 = cv2.threshold(img, 120 , 255 , cv2.THRESH_TOZERO_INV)

cv2.imshow( 'Binary Threshold' , thresh1)

cv2.imshow( 'Binary Threshold Inverted' , thresh2)

cv2.imshow( 'Truncated Threshold' , thresh3)

cv2.imshow( 'Set to 0' , thresh4)

cv2.imshow( 'Set to 0 Inverted' , thresh5)

if cv2.waitKey( 0 ) & 0xff = = 27 :

`` cv2.destroyAllWindows()

Input:

Output: