Cv2 threshold python что делает
Result is given below :

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.
It has three ‘special’ input params and only one output argument.
Adaptive Method — It decides how thresholding value is calculated.
- cv2.ADAPTIVE_THRESH_MEAN_C : threshold value is the mean of neighbourhood area.
- cv2.ADAPTIVE_THRESH_GAUSSIAN_C : threshold value is the weighted sum of neighbourhood values where weights are a gaussian window.
Block Size — It decides the size of neighbourhood area.
C — It is just a constant which is subtracted from the mean or weighted mean calculated.
Below piece of code compares global thresholding and adaptive thresholding for an image with varying illumination:

Otsu’s Binarization
In the first section, I told you there is a second parameter retVal. Its use comes when we go for Otsu’s Binarization. So what is it?
In global thresholding, we used an arbitrary value for threshold value, right? So, how can we know a value we selected is good or not? Answer is, trial and error method. But consider a bimodal image (In simple words, bimodal image is an image whose histogram has two peaks). For that image, we can approximately take a value in the middle of those peaks as threshold value, right ? That is what Otsu binarization does. So in simple words, it automatically calculates a threshold value from image histogram for a bimodal image. (For images which are not bimodal, binarization won’t be accurate.)
For this, our cv2.threshold() function is used, but pass an extra flag, cv2.THRESH_OTSU. For threshold value, simply pass zero. Then the algorithm finds the optimal threshold value and returns you as the second output, retVal. If Otsu thresholding is not used, retVal is same as the threshold value you used.
Check out below example. Input image is a noisy image. In first case, I applied global thresholding for a value of 127. In second case, I applied Otsu’s thresholding directly. In third case, I filtered image with a 5×5 gaussian kernel to remove the noise, then applied Otsu thresholding. See how noise filtering improves the result.
What is Thresholding?
![]()
Thresholding is a process of dividing an image into two (or more) classes of pixels, i.e. “foreground” and “background”. It is mostly used in various Image processing tasks, such as eliminating noise in the OCR process which allows greater image recognition accuracy, segmentation etc.
In order to obtain a thresholded image, usually, we convert the original image into a grayscale image and then apply the thresholding technique. This method is also known as Binarization as we convert the image into a binarized form, i.e. if the value of a pixel is lesser than the threshold value, convert it to 0(Black). If the value of a pixel is greater than the threshold value, convert it to 1(White) or vice-versa.
Let’s understand the importance of binarization with an example on OCR:
NOTE: For all my examples I am using pytesseract (a wrapper for google’s tesseract), Matplotlib and OpenCV.
Therefore please install all the above-mentioned libraries. For me, as I was working on a Colab Notebook, I need to install the pytesseract only.
And import them.
Okay, now suppose you have an image like below and you have to detect the text in it-
First, read the Image file, please make sure it is supported by OpenCV and then pass the object of this image to the image_to_string function as follows
As you can see the code has detected the right text. But will it perform the same on a noisy image like below?
Clearly, the output is not what you might have expected. let’s try the binary thresholding technique and then check the result.
From the above result, you might get the clue, why the threshold techniques are important in digital image processing tasks.
Simple Thresholding
If the pixel value is greater than a threshold value, it is assigned one value (maybe white), else it is assigned another value (maybe black). The function used is
- The first argument is the source image(grayscale image).
- The second argument is the threshold value which is used to classify the pixel values.
- The third argument is the maxVal which represents the value to be given if the pixel value is more than (sometimes less than) the threshold value.
- The fourth argument is the style of thresholding. OpenCV provides different styles of thresholding. Check the Documentation page.
Note:- Although we get the correct text for that image using simple threshold, however, this may not be the case with some other image. There we need to change the threshold value as accordingly or we need to perform some more operations to get the correct result.
Apart from the simple threshold, OpenCV provides more functions for thresholding such as Adaptive thresholding and Otsu’s Binarization.
Let’s check another example:-
Following is an image of a Shopfront.
First, open the image in grayscale mode and test the tesseract
Unfortunately, for this image, it didn’t output any text. So what went wrong?
It looks like the background cover more area than the texts, Let’s crop that particular area and then test again.
Again we can see that the result is not accurate, it didn’t detect ‘FOOD’ written at the bottom right of the image. Now this time I will try the Adaptive threshold. Following is the syntax for it.
Adaptive threshold
In this, the algorithm calculates the threshold for 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.
Though the code produces the correct text, yet it interprets noises as Characters as well. To overcome this, we need to blur the image a little bit and then test again.
Image blurring is achieved by convolving the image with a normalized box filter. It simply takes the average of all the pixels under the kernel area and replaces the central element with this average. This is done by the function cv2.blur(). It is useful for removing noise in the image. Blurring is a separate topic in itself, so I will cover it later in another post.
Conclusion
Image Thresholding is one of the most commonly used technique in many image processing tasks. However, we have to keep in mind that for perfect segmentation we need to try different threshold values.
Note:- Thresholding gives better results if the image is of higher contrast. Try to change the contrast value of the pixels and then apply the threshold.
In the end, I want you to try this by yourself and see what results you’ll get with different images. You can try to find other texts in the Shopfront image or try this image and share your reviews. Are you able to find the text in the image?
Hint: Try cv2.THRESH_BINARY in cv2.threshold() with thresh value = 1
For more details please check out this link and Notebook, it has an in-depth analysis of various thresholding techniques that you can also apply. Thanks to Ankit Kumar Singh for sharing his Notebook with us.
Image 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). The function used is cv2.threshold. First argument is the source image, which should be a grayscale image. Second argument is the threshold value which is used to classify the pixel values. Third argument is the maxVal which represents the value to be given if pixel value is more than (sometimes less than) the threshold value. OpenCV provides different styles of thresholding and it is decided by the fourth parameter of the function. Different types are:
- cv2.THRESH_BINARY
- cv2.THRESH_BINARY_INV
- cv2.THRESH_TRUNC
- cv2.THRESH_TOZERO
- cv2.THRESH_TOZERO_INV
Documentation clearly explain what each type is meant for. Please check out the documentation.
Two outputs are obtained. First one is a retval which will be explained later. Second output is our thresholded image.
To plot multiple images, we have used plt.subplot() function. Please checkout Matplotlib docs for more details.
Result is given below :

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.
It has three ‘special’ input params and only one output argument.
- cv2.ADAPTIVE_THRESH_MEAN_C : threshold value is the mean of neighbourhood area.
- cv2.ADAPTIVE_THRESH_GAUSSIAN_C : threshold value is the weighted sum of neighbourhood values where weights are a gaussian window.
Block Size — It decides the size of neighbourhood area.
C — It is just a constant which is subtracted from the mean or weighted mean calculated.
Below piece of code compares global thresholding and adaptive thresholding for an image with varying illumination:

Otsu’s Binarization¶
In the first section, I told you there is a second parameter retVal. Its use comes when we go for Otsu’s Binarization. So what is it?
In global thresholding, we used an arbitrary value for threshold value, right? So, how can we know a value we selected is good or not? Answer is, trial and error method. But consider a bimodal image (In simple words, bimodal image is an image whose histogram has two peaks). For that image, we can approximately take a value in the middle of those peaks as threshold value, right ? That is what Otsu binarization does. So in simple words, it automatically calculates a threshold value from image histogram for a bimodal image. (For images which are not bimodal, binarization won’t be accurate.)
For this, our cv2.threshold() function is used, but pass an extra flag, cv2.THRESH_OTSU . For threshold value, simply pass zero. Then the algorithm finds the optimal threshold value and returns you as the second output, retVal . If Otsu thresholding is not used, retVal is same as the threshold value you used.
Check out below example. Input image is a noisy image. In first case, I applied global thresholding for a value of 127. In second case, I applied Otsu’s thresholding directly. In third case, I filtered image with a 5×5 gaussian kernel to remove the noise, then applied Otsu thresholding. See how noise filtering improves the result.

How Otsu’s Binarization Works?¶
This section demonstrates a Python implementation of Otsu’s binarization to show how it works actually. If you are not interested, you can skip this.
Since we are working with bimodal images, Otsu’s algorithm tries to find a threshold value (t) which minimizes the weighted within-class variance given by the relation :


