OpenCV  4.3.0
Open Source Computer Vision
Image Thresholding

Goal

Simple Thresholding

Here, the matter is straight forward. If pixel value is greater than a threshold value, it is assigned one value (may be white), else it is assigned another value (may be black).

We use the function: cv.threshold (src, dst, thresh, maxval, type)

Parameters
srcinput array.
dstoutput array of the same size and type and the same number of channels as src.
threshthreshold value.
maxvalmaximum value to use with the cv.THRESH_BINARY and cv.THRESH_BINARY_INV thresholding types.
typethresholding type(see cv.ThresholdTypes).

thresholding type - OpenCV provides different styles of thresholding and it is decided by the fourth parameter of the function. Different types are:

Note
Input image should be single channel only in case of cv.THRESH_OTSU or cv.THRESH_TRIANGLE flags

Try it

Adaptive Thresholding

In the previous section, we used a global value as threshold value. But it may not be good in all the conditions where image has different lighting conditions in different areas. In that case, we go for adaptive thresholding. In this, the algorithm calculate the threshold for a small regions of the image. So we get different thresholds for different regions of the same image and it gives us better results for images with varying illumination.

We use the function: cv.adaptiveThreshold (src, dst, maxValue, adaptiveMethod, thresholdType, blockSize, C)

Parameters
srcsource 8-bit single-channel image.
dstdestination image of the same size and the same type as src.
maxValuenon-zero value assigned to the pixels for which the condition is satisfied
adaptiveMethodadaptive thresholding algorithm to use.
thresholdTypethresholding type that must be either cv.THRESH_BINARY or cv.THRESH_BINARY_INV.
blockSizesize of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.
Cconstant subtracted from the mean or weighted mean (see the details below). Normally, it is positive but may be zero or negative as well.

adaptiveMethod - It decides how thresholding value is calculated:

Try it