How to Equalize Histogram Using OpenCV in Computer Vision
To equalize a histogram in OpenCV, use the
cv2.equalizeHist() function on a grayscale image to enhance its contrast. For color images, convert to a color space like YUV, equalize the luminance channel, then convert back to BGR.Syntax
The main function to equalize histograms in OpenCV is cv2.equalizeHist(src).
src: Input grayscale image (8-bit single channel).- Returns: Output image with equalized histogram.
For color images, convert to YUV color space, equalize the Y channel, then convert back.
python
equalized_image = cv2.equalizeHist(src)
Example
This example shows how to load a grayscale image, apply histogram equalization with OpenCV, and display the original and equalized images.
python
import cv2 import numpy as np # Load image in grayscale img = cv2.imread('input.jpg', cv2.IMREAD_GRAYSCALE) # Check if image loaded if img is None: raise ValueError('Image not found or path is incorrect') # Apply histogram equalization equalized_img = cv2.equalizeHist(img) # Save results cv2.imwrite('original.jpg', img) cv2.imwrite('equalized.jpg', equalized_img) # Display images side by side combined = np.hstack((img, equalized_img)) cv2.imshow('Original (Left) vs Equalized (Right)', combined) cv2.waitKey(0) cv2.destroyAllWindows()
Output
A window opens showing the original grayscale image on the left and the histogram equalized image on the right with improved contrast.
Common Pitfalls
1. Applying equalizeHist directly on color images: This causes color distortion because it treats each channel independently.
2. Not converting color images to YUV or HSV before equalizing: Equalize only the luminance channel to preserve colors.
3. Using images with incorrect data types: equalizeHist requires 8-bit single channel images.
python
import cv2 # Wrong way: equalizing color image directly img_color = cv2.imread('color.jpg') equalized_wrong = cv2.equalizeHist(img_color) # This will error or distort colors # Right way: convert to YUV, equalize Y channel img_yuv = cv2.cvtColor(img_color, cv2.COLOR_BGR2YUV) img_yuv[:, :, 0] = cv2.equalizeHist(img_yuv[:, :, 0]) equalized_correct = cv2.cvtColor(img_yuv, cv2.COLOR_YUV2BGR)
Quick Reference
- Function:
cv2.equalizeHist()for grayscale images. - Color images: Convert to YUV, equalize Y channel, convert back.
- Input type: 8-bit single channel images only.
- Effect: Improves contrast by spreading pixel intensity distribution.
Key Takeaways
Use cv2.equalizeHist() on grayscale images to improve contrast easily.
For color images, equalize only the luminance channel in YUV color space to avoid color distortion.
Ensure input images are 8-bit single channel for histogram equalization.
Avoid applying equalizeHist directly on color images to prevent incorrect colors.
Histogram equalization spreads out pixel intensities to enhance image details.