Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

OpenCV Python Histogram Tutorial: Image Intensity Analysis & Visualization Guide

OpenCV Python – Histogram

Histograms are a powerful tool in image processing used to analyze the distribution of pixel intensities in an image. They help us understand how brightness and contrast are distributed across an image.

In OpenCV Python, histograms are widely used for image enhancement, thresholding, and feature analysis.


1. What is an Image Histogram?

An image histogram is a graphical representation of pixel intensity distribution.

  • X-axis → Pixel intensity (0 to 255)
  • Y-axis → Number of pixels

It helps in understanding:

  • Brightness
  • Contrast
  • Image quality

2. Import OpenCV and Matplotlib

import cv2
import matplotlib.pyplot as plt

3. Read Image in Grayscale

img = cv2.imread("image.jpg", cv2.IMREAD_GRAYSCALE)

cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

4. Calculate Histogram using OpenCV

Syntax:

cv2.calcHist(images, channels, mask, histSize, ranges)

Example:

hist = cv2.calcHist([img], [0], None, [256], [0, 256])

5. Plot Histogram using Matplotlib

plt.plot(hist)
plt.title("Grayscale Histogram")
plt.xlabel("Pixel Intensity")
plt.ylabel("Number of Pixels")
plt.show()

6. Histogram of Color Image

img = cv2.imread("image.jpg")

colors = ('b', 'g', 'r')

for i, color in enumerate(colors):
hist = cv2.calcHist([img], [i], None, [256], [0, 256])
plt.plot(hist, color=color)

plt.title("Color Histogram")
plt.xlabel("Pixel Intensity")
plt.ylabel("Frequency")
plt.show()

7. Histogram with Mask

mask = cv2.inRange(img, (0,0,0), (255,255,255))

hist = cv2.calcHist([img], [0], mask, [256], [0, 256])

8. Histogram Equalization

Improves image contrast.

gray = cv2.imread("image.jpg", cv2.IMREAD_GRAYSCALE)

equalized = cv2.equalizeHist(gray)

cv2.imshow("Equalized Image", equalized)
cv2.waitKey(0)
cv2.destroyAllWindows()

9. Why Histogram is Important

Histograms are used in:

  • Image enhancement
  • Object detection
  • Face recognition
  • Medical image analysis
  • Computer vision preprocessing

10. Common Mistakes

❌ Using wrong image format

✔ Solution:

  • Use grayscale for single-channel histogram

❌ Empty histogram output

✔ Solution:

  • Check image path and loading

11. Conclusion

Histograms in OpenCV Python are essential for analyzing image brightness and contrast. They help in improving image quality and are widely used in advanced computer vision applications.

Once you understand histograms, you can move to image enhancement techniques like equalization and segmentation.




Post a Comment

0 Comments