🐶
Machine Vision

OpenCV Auto Contrast and Brightness for Documents

By Jan on 02/18/2025

Learn how to use OpenCV to automatically adjust the contrast and brightness of color photos of paper documents for improved readability and image processing.

OpenCV Auto Contrast and Brightness for Documents

Table of Contents

Introduction

This article provides a step-by-step guide on how to enhance image contrast using histogram equalization in Python. The code utilizes the OpenCV library to manipulate and process the image.

Step-by-Step Guide

  1. Import necessary libraries:
import cv2
  1. Load the image:
image = cv2.imread('input.jpg')
  1. Convert the image to grayscale:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  1. Apply Gaussian blur to reduce noise:
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
  1. Calculate the histogram of the blurred image:
hist = cv2.calcHist([blurred], [0], None, [256], [0, 256])
  1. Find the minimum and maximum pixel values from the histogram:
min_val, max_val, _, _ = cv2.minMaxLoc(hist)
  1. Apply contrast stretching using the min-max values:
output = cv2.convertScaleAbs(gray, alpha=255.0/(max_val - min_val), beta=-min_val * 255.0/(max_val - min_val))
  1. Display the original and enhanced images:
cv2.imshow('Original', image)
cv2.imshow('Enhanced', output)
cv2.waitKey(0)

Explanation:

  • This code snippet enhances the contrast of an image using histogram equalization.
  • It first converts the image to grayscale and applies Gaussian blur to reduce noise.
  • Then, it calculates the histogram of the blurred image to determine the distribution of pixel intensities.
  • The minimum and maximum pixel values are extracted from the histogram.
  • Finally, contrast stretching is applied using the min-max values to enhance the image's contrast.
  • The alpha value controls the contrast, and the beta value controls the brightness.

Code Example

The Python code enhances the contrast of an image using contrast stretching. It reads an image, converts it to grayscale, applies Gaussian blur, calculates the histogram, finds minimum and maximum pixel values, performs contrast stretching based on these values, and finally displays both the original and enhanced images.

import cv2

# Load the image
image = cv2.imread('input.jpg')

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

# Apply Gaussian blur to reduce noise
blurred = cv2.GaussianBlur(gray, (5, 5), 0)

# Calculate the histogram of the blurred image
hist = cv2.calcHist([blurred], [0], None, [256], [0, 256])

# Find the minimum and maximum pixel values from the histogram
min_val, max_val, _, _ = cv2.minMaxLoc(hist)

# Apply contrast stretching using the min-max values
output = cv2.convertScaleAbs(gray, alpha=255.0/(max_val - min_val), beta=-min_val * 255.0/(max_val - min_val))

# Display the original and enhanced images
cv2.imshow('Original', image)
cv2.imshow('Enhanced', output)
cv2.waitKey(0)

Explanation:

  1. Import necessary libraries:

    • cv2: OpenCV library for image processing.
  2. Load the image:

    • cv2.imread('input.jpg'): Loads the image named "input.jpg" from the current directory.
  3. Convert the image to grayscale:

    • cv2.cvtColor(image, cv2.COLOR_BGR2GRAY): Converts the color image to grayscale.
  4. Apply Gaussian blur to reduce noise:

    • cv2.GaussianBlur(gray, (5, 5), 0): Applies a Gaussian blur with a kernel size of (5, 5) to the grayscale image.
  5. Calculate the histogram of the blurred image:

    • cv2.calcHist([blurred], [0], None, [256], [0, 256]): Calculates the histogram of the blurred image.
  6. Find the minimum and maximum pixel values from the histogram:

    • cv2.minMaxLoc(hist): Finds the minimum and maximum pixel values and their locations in the histogram.
  7. Apply contrast stretching using the min-max values:

    • cv2.convertScaleAbs(gray, alpha=255.0/(max_val - min_val), beta=-min_val * 255.0/(max_val - min_val)): Applies contrast stretching to the grayscale image using the calculated min-max values.
      • alpha: Controls the contrast.
      • beta: Controls the brightness.
  8. Display the original and enhanced images:

    • cv2.imshow('Original', image): Displays the original image.
    • cv2.imshow('Enhanced', output): Displays the enhanced image.
    • cv2.waitKey(0): Waits for a key press to close the image windows.

Additional Notes

General:

  • Purpose: This code demonstrates a basic form of image enhancement by increasing the global contrast of the image. This can make details more visible, especially in images with poor lighting or low dynamic range.
  • Limitations: This method is not suitable for all images. It can amplify noise and may not be effective for images with already good contrast.
  • Alternatives: More sophisticated contrast enhancement techniques include:
    • Adaptive Histogram Equalization (AHE): Improves local contrast.
    • Contrast Limited Adaptive Histogram Equalization (CLAHE): Similar to AHE but limits amplification of noise.
    • Gamma Correction: Adjusts image brightness and contrast non-linearly.

Code Specific:

  • cv2.imread(): The second argument of cv2.imread() determines the color space. Use cv2.IMREAD_COLOR for color images and cv2.IMREAD_GRAYSCALE for grayscale.
  • Gaussian Blur: The kernel size in cv2.GaussianBlur() affects the degree of blurring. Larger kernels result in stronger blurring.
  • Histogram Calculation: The cv2.calcHist() function is used to calculate the image histogram. Understanding histograms is crucial for image processing.
  • Contrast Stretching Formula: The formula used for contrast stretching maps the original pixel values to a new range (0-255) based on the minimum and maximum values.
  • cv2.convertScaleAbs(): This function scales, calculates absolute values, and converts the result to 8-bit unsigned integers (suitable for image display).
  • Displaying Images: The cv2.waitKey(0) function is essential to keep the image windows open until a key is pressed.

Further Exploration:

  • Experiment with different images and observe the effects of contrast stretching.
  • Try different kernel sizes for Gaussian blur and analyze the impact on the output.
  • Implement and compare the results with AHE and CLAHE.
  • Explore gamma correction as an alternative contrast enhancement technique.

Summary

This code snippet demonstrates how to enhance the contrast of an image using histogram equalization in Python with OpenCV (cv2).

Here's a breakdown of the process:

  1. Image Preprocessing:

    • Load the image (cv2.imread).
    • Convert it to grayscale (cv2.cvtColor).
    • Apply Gaussian blur to reduce noise (cv2.GaussianBlur).
  2. Histogram Calculation:

    • Calculate the histogram of the blurred image to understand the distribution of pixel intensities (cv2.calcHist).
  3. Contrast Stretching:

    • Find the minimum and maximum pixel values from the histogram (cv2.minMaxLoc).
    • Apply contrast stretching using these values to enhance the image's contrast (cv2.convertScaleAbs). This involves scaling pixel intensities to utilize the full range (0-255).
  4. Display:

    • Show the original and enhanced images side-by-side (cv2.imshow).

In essence, this code analyzes the image's pixel intensity distribution and then stretches it to cover the entire spectrum, resulting in a more visually appealing image with enhanced contrast.

Conclusion

This code demonstrates a simple yet effective method for enhancing image contrast using histogram equalization in Python. By leveraging the OpenCV library, the code efficiently manipulates image data, applies Gaussian blur for noise reduction, calculates the histogram to understand pixel intensity distribution, and performs contrast stretching to improve visual clarity. This example provides a foundation for understanding basic image processing techniques and can serve as a starting point for exploring more advanced contrast enhancement methods like AHE, CLAHE, and gamma correction.

References

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait