Last modified: Jan 16, 2025 By Alexander Williams

Python OpenCV cv2.adaptiveThreshold() Guide

Image thresholding is a key step in image processing. It helps in separating objects from the background. OpenCV provides the cv2.adaptiveThreshold() function for adaptive thresholding.

Unlike cv2.threshold(), which uses a global threshold value, cv2.adaptiveThreshold() calculates thresholds for smaller regions. This makes it ideal for images with varying lighting conditions.

What is cv2.adaptiveThreshold()?

The cv2.adaptiveThreshold() function applies an adaptive threshold to an image. It computes a threshold for each pixel based on its neighborhood. This is useful for images with uneven lighting.

The function has the following syntax:


    cv2.adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C)
    

Parameters:

  • src: Input image (grayscale).
  • maxValue: Maximum value assigned to pixels exceeding the threshold.
  • adaptiveMethod: Method to calculate the threshold (e.g., cv2.ADAPTIVE_THRESH_MEAN_C).
  • thresholdType: Type of thresholding (e.g., cv2.THRESH_BINARY).
  • blockSize: Size of the neighborhood area.
  • C: Constant subtracted from the mean or weighted mean.

Example: Using cv2.adaptiveThreshold()

Let’s apply adaptive thresholding to an image. First, ensure you have OpenCV installed. Use the following code:


    import cv2
    import numpy as np

    # Load an image in grayscale
    image = cv2.imread('image.jpg', 0)

    # Apply adaptive thresholding
    adaptive_thresh = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)

    # Display the result
    cv2.imshow('Adaptive Threshold', adaptive_thresh)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

This code loads an image, applies adaptive thresholding, and displays the result. The blockSize is set to 11, and C is 2.

Output Explanation

The output will be a binary image. Pixels above the local threshold will be white (255), and others will be black (0). This method works well for images with uneven lighting.


    Output: A binary image with adaptive thresholding applied.
    

When to Use cv2.adaptiveThreshold()?

Use cv2.adaptiveThreshold() when dealing with images with varying lighting. It’s better than cv2.threshold() for such cases. It’s also useful in document scanning and object detection.

Combining with Other Functions

You can combine cv2.adaptiveThreshold() with other OpenCV functions. For example, use cv2.drawContours() to highlight detected objects. This enhances image processing workflows.

Conclusion

The cv2.adaptiveThreshold() function is a powerful tool for image thresholding. It adapts to local image regions, making it ideal for uneven lighting. Use it in your projects to improve object detection and image analysis.