Python | Threshold Methods Using OpenCV | Set-3 (Otsu Trasholding)



In Otsu Thresholding , the threshold value is not selected, but is determined automatically. A bimodal image (two different image values) is considered. The generated histogram contains two peaks. So a general condition would be to choose a threshold that is in the middle of both peaks of the histogram.

We use the traditional cv2.threshold function and use cv2.THRESH_OTSU as an optional flag.

Syntax: cv2.threshold (source, thresholdValue, maxVal , thresholdingTechnique)

Parameters:
– & gt;  source : Input Image array (must be in Grayscale).
– & gt;  thresholdValue : Value of Threshold below and above which pixel values ​​will change accordingly.
– & gt;  maxVal : Maximum value that can be assigned to a pixel.
– & gt;  thresholdingTechnique : The type of thresholding to be applied.

Below is the Python code explaining the father-threshold technique —

# Python program for illustration
# Type of otsu threshold in the image

 
# organization of import

import cv2 

import numpy as np 

 
# the path to the input image is specified and
# the image is loaded using the imread command

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

 
# cv2.cvtColor is applied over
# image input with parameters applied
# convert image to grayscale

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

  
# application Otsu threshold
# as an optional flag in binary
# threshold

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

< code class = "undefined spaces">  cv2.THRESH_OTSU) 

 
# window with the displayed image
# with an appropriate threshold
# methods applied to the input image

cv2.imshow ( `Otsu Threshold` , thresh1) 

 
# Cancel allocating any associated memory usage

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

cv2.destroyAllWindows () 

Input data :

Exit:

The calculation assumes that the image contains two classes of pixels, following the pixels of the foreground and background, at which point an ideal limit is set, isolating the two classes in order to be consolidated the spread was negligible.