An image histogram is a graphical representation of pixel intensity distribution. Histogram analysis helps in understanding image contrast, brightness, and intensity spread. Histogram equalization is a technique used to improve the contrast of an image.
OpenCV provides cv2.calcHist() to calculate image histograms.
Histograms are often visualized using Matplotlib.
import cv2
import matplotlib.pyplot as plt
img = cv2.imread("sample.jpg", cv2.IMREAD_GRAYSCALE)
# Calculate histogram
hist = cv2.calcHist([img], [0], None, [256], [0,256])
# Plot histogram
plt.plot(hist)
plt.title("Image Histogram")
plt.xlabel("Pixel Intensity")
plt.ylabel("Frequency")
plt.show()
Histogram equalization enhances the contrast of an image by redistributing pixel intensities.
Use cv2.equalizeHist() for grayscale images.
# Apply histogram equalization
equalized = cv2.equalizeHist(img)
cv2.imshow("Original", img)
cv2.imshow("Equalized", equalized)
cv2.waitKey(0)
cv2.destroyAllWindows()
For better local contrast enhancement, use CLAHE. It prevents over-amplification of noise in uniform areas.
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
clahe_img = clahe.apply(img)
cv2.imshow("CLAHE Equalized", clahe_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
✅ In this lesson, you learned how to calculate image histograms and apply
histogram equalization using OpenCV.
These techniques are essential for contrast enhancement, medical imaging, and preprocessing before feature extraction.
👉 Next, we will explore feature detection techniques (Harris, SIFT, ORB).
