OpenCV Tutorial

Image Processing

Feature Detection and Description

Drawing Functions

Video Processing

Applications and Projects

Adaptive Thresholding in OpenCV

Adaptive thresholding is a method where the threshold value is not global but is calculated for smaller regions. This method can give better results when the image has varying illumination, as a single global threshold might not work well for all regions.

In OpenCV, you can perform adaptive thresholding using the cv2.adaptiveThreshold() function.

Adaptive Thresholding in OpenCV:

1. Setup:

Ensure OpenCV is installed:

pip install opencv-python

Now, import the required libraries:

import cv2

2. Read the Image & Convert to Grayscale:

Adaptive thresholding is typically performed on grayscale images:

# Read the image
image = cv2.imread('path_to_image.jpg')

# Convert to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

3. Apply Adaptive Thresholding:

Use the cv2.adaptiveThreshold() function:

thresh = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, 
                               cv2.THRESH_BINARY, 11, 2)

Here:

  • gray_image is the input grayscale image.
  • 255 is the max value, typically representing white.
  • cv2.ADAPTIVE_THRESH_MEAN_C indicates we're using the mean of the neighborhood area minus the constant (in this case, 2) to calculate the threshold.
  • cv2.THRESH_BINARY is the type of thresholding, resulting in a binary image.
  • 11 is the block size, defining the size of the neighborhood area.
  • 2 is the constant subtracted from the mean.

Another adaptive method provided by OpenCV is cv2.ADAPTIVE_THRESH_GAUSSIAN_C, where the threshold value is the weighted sum of neighborhood values where weights are a Gaussian window.

4. Display the Result:

cv2.imshow('Original Image', gray_image)
cv2.imshow('Adaptive Threshold', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()

Complete Code:

Here's a complete script for adaptive thresholding using the mean:

import cv2

# Load the image and convert to grayscale
image = cv2.imread('path_to_image.jpg')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

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

# Display the result
cv2.imshow('Original Image', gray_image)
cv2.imshow('Adaptive Threshold', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()

Replace 'path_to_image.jpg' with the path to your image file and run the script. The original grayscale and adaptively thresholded images will be displayed side by side.

Feel free to experiment with different block sizes and constants to optimize for specific images.

  1. Adaptive thresholding in OpenCV using Python:

    import cv2
    
    # Read an image in grayscale
    img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
    
    # Apply adaptive thresholding
    adaptive_thresh = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
    
    # Display the original and adaptive thresholded images
    cv2.imshow('Original Image', img)
    cv2.imshow('Adaptive Thresholded Image', adaptive_thresh)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
  2. Adaptive thresholding vs. global thresholding in OpenCV:

    import cv2
    
    # Read an image in grayscale
    img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
    
    # Global thresholding
    _, global_thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
    
    # Adaptive thresholding
    adaptive_thresh = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
    
    # Display the original, global thresholded, and adaptive thresholded images
    cv2.imshow('Original Image', img)
    cv2.imshow('Global Thresholded Image', global_thresh)
    cv2.imshow('Adaptive Thresholded Image', adaptive_thresh)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
  3. Different adaptive thresholding algorithms in OpenCV:

    import cv2
    
    img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
    
    # Adaptive thresholding using MEAN algorithm
    adaptive_mean_thresh = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
    
    # Adaptive thresholding using GAUSSIAN algorithm
    adaptive_gaussian_thresh = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
    
    # Display the original and adaptive thresholded images using different algorithms
    cv2.imshow('Original Image', img)
    cv2.imshow('Adaptive Mean Thresholded Image', adaptive_mean_thresh)
    cv2.imshow('Adaptive Gaussian Thresholded Image', adaptive_gaussian_thresh)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
  4. Choosing appropriate block sizes for adaptive thresholding: The blockSize parameter in adaptive thresholding determines the size of the neighborhood for calculating the threshold. Experiment with different values to find the most suitable block size for your images.

    import cv2
    
    img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
    
    # Try different block sizes for adaptive thresholding
    block_size_1 = 3
    block_size_2 = 11
    
    adaptive_thresh_1 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, block_size_1, 2)
    adaptive_thresh_2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, block_size_2, 2)
    
    # Display the original and adaptive thresholded images with different block sizes
    cv2.imshow('Original Image', img)
    cv2.imshow('Adaptive Thresholded Image (Block Size {})'.format(block_size_1), adaptive_thresh_1)
    cv2.imshow('Adaptive Thresholded Image (Block Size {})'.format(block_size_2), adaptive_thresh_2)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
  5. Real-time adaptive thresholding in OpenCV:

    import cv2
    
    cap = cv2.VideoCapture(0)  # Use webcam, or replace with video path
    
    while True:
        ret, frame = cap.read()
        if not ret:
            break
    
        # Convert the frame to grayscale
        gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
        # Apply adaptive thresholding
        adaptive_thresh = cv2.adaptiveThreshold(gray_frame, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
    
        # Display the original and thresholded frames
        cv2.imshow('Original Frame', frame)
        cv2.imshow('Adaptive Thresholded Frame', adaptive_thresh)
    
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    cap.release()
    cv2.destroyAllWindows()
    
  6. Adaptive thresholding for image segmentation in OpenCV:

    import cv2
    
    img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
    
    # Apply adaptive thresholding for image segmentation
    adaptive_thresh = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
    
    # Perform additional processing on the segmented image as needed
    
    # Display the original and segmented images
    cv2.imshow('Original Image', img)
    cv2.imshow('Segmented Image', adaptive_thresh)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
  7. Adaptive thresholding for noise reduction in OpenCV:

    import cv2
    
    img = cv2.imread('noisy_image.jpg', cv2.IMREAD_GRAYSCALE)
    
    # Apply adaptive thresholding for noise reduction
    adaptive_thresh = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
    
    # Display the original and thresholded images
    cv2.imshow('Original Image', img)
    cv2.imshow('Adaptive Thresholded Image', adaptive_thresh)
    cv2.waitKey(0)
    cv2.destroyAllWindows()