Learn how to use OpenCV to automatically adjust the contrast and brightness of color photos of paper documents for improved readability and image processing.
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.
import cv2
image = cv2.imread('input.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
hist = cv2.calcHist([blurred], [0], None, [256], [0, 256])
min_val, max_val, _, _ = cv2.minMaxLoc(hist)
output = cv2.convertScaleAbs(gray, alpha=255.0/(max_val - min_val), beta=-min_val * 255.0/(max_val - min_val))
cv2.imshow('Original', image)
cv2.imshow('Enhanced', output)
cv2.waitKey(0)
Explanation:
alpha
value controls the contrast, and the beta
value controls the brightness.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:
Import necessary libraries:
cv2
: OpenCV library for image processing.Load the image:
cv2.imread('input.jpg')
: Loads the image named "input.jpg" from the current directory.Convert the image to grayscale:
cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
: Converts the color image to grayscale.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.Calculate the histogram of the blurred image:
cv2.calcHist([blurred], [0], None, [256], [0, 256])
: Calculates the histogram of the blurred image.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.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.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.General:
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.cv2.GaussianBlur()
affects the degree of blurring. Larger kernels result in stronger blurring.cv2.calcHist()
function is used to calculate the image histogram. Understanding histograms is crucial for image processing.cv2.convertScaleAbs()
: This function scales, calculates absolute values, and converts the result to 8-bit unsigned integers (suitable for image display).cv2.waitKey(0)
function is essential to keep the image windows open until a key is pressed.Further Exploration:
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:
Image Preprocessing:
cv2.imread
).cv2.cvtColor
).cv2.GaussianBlur
).Histogram Calculation:
cv2.calcHist
).Contrast Stretching:
cv2.minMaxLoc
).cv2.convertScaleAbs
). This involves scaling pixel intensities to utilize the full range (0-255).Display:
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.
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.