๐ŸŒ
PyImageSearch
pyimagesearch.com โ€บ home โ€บ blog โ€บ adaptive thresholding with opencv ( cv2.adaptivethreshold )
Adaptive Thresholding with OpenCV ( cv2.adaptiveThreshold ) - PyImageSearch
June 9, 2023 - We have a single Python script to review today, adaptive_thresholding.py. Weโ€™ll apply this script to our example image, steve_jobs.png, which will show compare and contrast the results of: ... Letโ€™s get started! We are now ready to implement adaptive threshold with OpenCV! Open the adaptive_thresholding.py file in your project directory and letโ€™s get to work: # import the necessary packages import argparse import cv2 # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", type=str, required=True, help="path to input image") args = vars(ap.parse_args())
Discussions

Shape Detection with Adaptive Thresholding in Python/OpenCV - Stack Overflow
As fmw42 mentioned, the best answers are the simplest. cv2.adaptiveThreshold is not an easy function to use and in this case, the obvious approach should be to go with colour channels instead of dynamic thresholds More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to make adaptive Threshold at part on image in Opencv python? - Stack Overflow
Here is one solution for the desired region in Python/OpenCV. It is to use division normalization rather than adaptive thresholding. (This may or may not work for other regions.) ... Copyimport cv2 import numpy as np # read the input img = cv2.imread('equador.png') # specify the crop rectangle ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - OpenCV output of Adaptive Threshold - Stack Overflow
I am a newbie in android, and open CV both. However, I am trying to take an image from the camera, convert it into the desired format, and pass it to the tflite model. Code for capturing image, and More on stackoverflow.com
๐ŸŒ stackoverflow.com
Adaptive threshold parameter estimation - Python - OpenCV
My project requires choosing the right parameters for cv2.adaptiveThreshold(): blockSize and C for many images. The project consists of 21 directories with approximately 100 frames each. Every frame is unique. After the threshold, there should be an image left where the crystals (the white ... More on forum.opencv.org
๐ŸŒ forum.opencv.org
0
May 12, 2021
๐ŸŒ
OpenCV
docs.opencv.org โ€บ 4.13.0 โ€บ d7 โ€บ d4d โ€บ tutorial_py_thresholding.html
OpenCV: Image Thresholding
The code below compares global thresholding and adaptive thresholding for an image with varying illumination: import cv2 as cv ยท import numpy as np ยท from matplotlib import pyplot as plt ยท
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ opencv-adaptive-thresholding-in-python-with-cv2adaptivethreshold
OpenCV Adaptive Thresholding in Python with cv2.adaptiveThreshold()
November 16, 2023 - Let's try segmenting the characters in the same image as before, using adaptive thresholding: ... Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it! ... # Read and prepare image img = cv2.imread('book.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (7, 7), 0) # Apply adaptive thresholding mask = cv2.adaptiveThreshold(blurred, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 31, 10) # Plot results fig, ax = plt.subplots(1, 2, figsize=(12, 5)) ax[0].imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) ax[1].imshow(cv2.cvtColor(mask, cv2.COLOR_BGR2RGB)) plt.tight_layout()
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-thresholding-techniques-using-opencv-set-2-adaptive-thresholding
Adaptive Thresholding using OpenCV - GeeksforGeeks
December 3, 2025 - The threshold for each pixel is computed as the mean value of the surrounding block (199ร—199 neighborhood, here), minus the constant (5). Best for images with fairly consistent noise or lighting within local regions.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ opencv โ€บ opencv_adaptive_threshold.htm
OpenCV - Adaptive Threshold
In OpenCV, you can perform Adaptive threshold operation on an image using the method adaptiveThreshold() of the Imgproc class.
๐ŸŒ
Python Programming
pythonprogramming.net โ€บ thresholding-image-analysis-python-opencv-tutorial
Thresholding OpenCV Python Tutorial
import cv2 import numpy as np th = cv2.adaptiveThreshold(grayscaled, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1) cv2.imshow('original',img) cv2.imshow('Adaptive threshold',th) cv2.waitKey(0) cv2.destroyAllWindows() There is another version of thresholding that one can do, called Otsu's threshold. It doesn't serve us well here, but: retval2,threshold2 = cv2.threshold(grayscaled,125,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) cv2.imshow('original',img) cv2.imshow('Otsu threshold',threshold2) cv2.waitKey(0) cv2.destroyAllWindows() The next tutorial: Color Filtering OpenCV Python Tutorial
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ effective adaptive thresholding techniques in python with opencv
Effective Adaptive Thresholding Techniques in Python with OpenCV - Be on the Right Side of Change
February 28, 2024 - The block size and constant in the cv2.adaptiveThreshold() remain the same as in Method 1, but now they relate to a Gaussian window. For a quick and concise implementation, you can perform adaptive thresholding in Python using a one-liner that reads, applies thresholding, and displays the result.
Find elsewhere
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-perform-adaptive-mean-and-gaussian-thresholding-of-an-image-using-python-opencv
OpenCV Python - Image Threshold
September 27, 2022 - In the example below, the original image (messi.jpg is applied with mean and Gaussian adaptive thresholding. import cv2 as cv import numpy as np from matplotlib import pyplot as plt img = cv.imread('messi.jpg',0) img = cv.medianBlur(img,5) th1 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_MEAN_C,\ cv.THRESH_BINARY,11,2) th2 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,\ cv.THRESH_BINARY,11,2) titles = ['Original', 'Mean Thresholding', 'Gaussian Thresholding'] images = [img, th1, th2] for i in range(3): plt.subplot(2,2,i+1),plt.imshow(images[i],'gray') plt.title(titles[i]) plt.xticks([]),plt.yticks([]) plt.show()
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ opencv-thresholding-in-python-with-cv2threshold
OpenCV Thresholding in Python with cv2.threshold()
November 17, 2023 - Another way to overcome some of the issues with basic thresholding with a single threshold value is to use adaptive thresholding which applies a threshold value on each small region in an image, rather than globally.
๐ŸŒ
Medium
medium.com โ€บ featurepreneur โ€บ dive-deeper-into-opencvs-adaptive-thresholding-3f29dda8c908
Dive deeper into OpenCVโ€™s Adaptive Thresholding | by Maximin Joshua | featurepreneur | Medium
December 1, 2021 - Then depending on the threshold type passed, either one of the following operations in the below image is performed: ... import cv2 as cv#read an image and convert it to grayscale img = cv.imread('D://medium_blogs//phone_dimmed4.jpg') gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)#apply normal and adaptive thresholding to the image ret, thresh = cv.threshold(gray, 70, 255, cv.THRESH_BINARY) adapt = cv.adaptiveThreshold(gray,255,cv.ADAPTIVE_THRESH_MEAN_C,cv.THRESH_BINARY,99,3)#create resizable windows for the images to be displayed cv.namedWindow('adapt',cv.WINDOW_NORMAL) cv.namedWindow('thresh', cv.WINDOW_NORMAL)#show the image cv.imshow('thresh', thresh) cv.imshow('adapt', adapt)if cv.waitKey(0): cv.destroyAllWindows()
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 77978648 โ€บ shape-detection-with-adaptive-thresholding-in-python-opencv
Shape Detection with Adaptive Thresholding in Python/OpenCV - Stack Overflow
ts_img = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY,11,2) but what I get is just the edges of figure with a lot of noise, for example the edges of the title. Is there a way to get just the black filled rectangle that represents the book on white background? Thanks! ... Try cv2.inRange() thresholding to get the blue color of the color in place of adaptive thresholding.
๐ŸŒ
Python Geeks
pythongeeks.org โ€บ python geeks โ€บ learn opencv โ€บ thresholding in opencv
Thresholding in OpenCV - Python Geeks
October 11, 2022 - Adaptive thresholding at pixel level yields superior results as compared to global thresholding, particularly in cases where the image has regions of varying levels of contrasts. In OpenCV, cv2.adaptiveThreshold() is used for adaptive thresholding.
Top answer
1 of 1
5

The main issue is that the result of adaptiveThreshold has gaps in the external edge, so you can't use it as input to findContours.

I think that using GaussianBlur makes things worst, because it blurs the edge between the hand and the background.

You may use the following stages:

  • Convert frame to Grayscale.
  • Apply adaptiveThreshold with large kernel size (I used size 51).
    Using a large kernel size, keeps a thick edge line without gaps (except from a small gap at the fingernail).
  • Find contours.
    Find the contour with the maximum area.
  • Draw the contour (fill with solid value of 255) on a zeros image.
    There is a problem: the inner part of the hand is not filled due to the weird shape of the contour.
  • For complete the filling:
    Find the center of the contour, and fill it using floodFill.

Here is a Python code sample:

import numpy as np
import cv2

frame = cv2.imread("hand.jpg")  # Read image from file (for testing).

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  # Use BGR to Gray conversion (not RGBA, because image is read from file)

# Apply adaptiveThreshold with large filter size.
thres_gray = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 51, 2)

# Find contours (external contours)
cnts, hier = cv2.findContours(thres_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

# Find contour with the maximum area
c = max(cnts, key=cv2.contourArea)

res = np.zeros_like(gray)  # Create new zeros images for storing the result.

# Fill the contour with white color - draw the filled contour on res image.
cv2.drawContours(res, [c], -1, 255, -1)

# Compute the center of the contour
# https://www.pyimagesearch.com/2016/02/01/opencv-center-of-contour/
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])

# Use floodFill for filling the center of the contour
cv2.floodFill(res, None, (cX, cY), 255)

# Show images for testing
cv2.imshow('thres_gray', thres_gray)
cv2.imshow('res', res)
cv2.waitKey()
cv2.destroyAllWindows()

Results:

thres_gray:

res before floodFill:

res after floodFill:


JAVA implementation:

package myproject;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.CvType;
import org.opencv.core.Scalar;
import org.opencv.core.Point;
import org.opencv.core.MatOfPoint;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgproc.Moments;
import org.opencv.imgcodecs.Imgcodecs;
import java.util.List;
import java.util.ArrayList;

class Sample {
    

static { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }


  
public static void main(String[] args) {
    Mat frame = Imgcodecs.imread("hand.jpg");
    
    Mat gray = new Mat();
    Mat thres_gray = new Mat();
    
    Imgproc.cvtColor(frame, gray, Imgproc.COLOR_BGR2GRAY);
    
    //Apply adaptiveThreshold with large filter size.
    Imgproc.adaptiveThreshold(gray, thres_gray, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY_INV, 51, 2);    
      
    List<MatOfPoint> contours = new ArrayList<>();
    Mat hierarchy = new Mat();
    
    //Find contours
    Imgproc.findContours(thres_gray, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE);

    //Find contour with the maximum area
    //https://stackoverflow.com/questions/38759925/how-to-find-largest-contour-in-java-opencv
    double maxVal = 0;
    int maxValIdx = 0;
    for (int contourIdx = 0; contourIdx < contours.size(); contourIdx++)
    {
        double contourArea = Imgproc.contourArea(contours.get(contourIdx));
        if (maxVal < contourArea)
        {
            maxVal = contourArea;
            maxValIdx = contourIdx;
        }
    }
       
    Mat res = Mat.zeros(gray.size(), CvType.CV_8UC1);    //Create new zeros images for storing the result.
    
    Imgproc.drawContours(res, contours, maxValIdx, new Scalar(255), -1);
    
    //Compute the center of the contour
    //https://www.pyimagesearch.com/2016/02/01/opencv-center-of-contour/
    Moments M = Imgproc.moments(contours.get(maxValIdx));
    int cX = (int)(M.get_m10() / M.get_m00());
    int cY = (int)(M.get_m01() / M.get_m00());    

    //Use floodFill for filling the center of the contour.    
    Mat mask = Mat.zeros(res.rows() + 2, res.cols() + 2, CvType.CV_8UC1);
    Imgproc.floodFill(res, mask, new Point(cX, cY), new Scalar(255));
       
    Imgcodecs.imwrite("res.png", res);
}

}
๐ŸŒ
OpenCV
forum.opencv.org โ€บ python
Adaptive threshold parameter estimation - Python - OpenCV
May 12, 2021 - My project requires choosing the right parameters for cv2.adaptiveThreshold(): blockSize and C for many images. The project consists of 21 directories with approximately 100 frames each. Every frame is unique. After the threshold, there should be an image left where the crystals (the white ...
๐ŸŒ
Medium
medium.com โ€บ @amit25173 โ€บ opencv-adaptive-threshold-fae667b91984
OpenCV Adaptive Threshold | by Amit Yadav | Medium
April 18, 2025 - The heart of the function lies in the adaptiveMethod parameter, where you decide how the thresholding is calculated locally: cv2.ADAPTIVE_THRESH_MEAN_C: This method calculates the threshold based on the mean of the local neighborhood pixels.
๐ŸŒ
GitHub
gist.github.com โ€บ pknowledge โ€บ 6fd9944c2345b8872b8917257f88a7d1
Adaptive Thresholding Image - OpenCV Python ยท GitHub
It seems that the image that is fetched is not in grayscale and has to be converted to grayscale first. You can try converting the image to grayscale first use the below piece of code : img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ath2 = cv2.adaptiveThreshold(img_grey,255,cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY,11,2) This worked for me.
๐ŸŒ
YouTube
youtube.com โ€บ watch
Python OpenCV Thresholding: From Simple to Adaptive in Minutes! - YouTube
Want to master image thresholding in OpenCV? In this video, we break it down from basic thresholding to adaptive thresholding, helping you transform images l...
Published: March 30, 2025