0
0
Computer-visionConceptBeginner · 3 min read

Histogram in OpenCV: What It Is and How It Works

In computer vision, a histogram in OpenCV is a graphical representation of the distribution of pixel intensities in an image. It shows how many pixels have each brightness value, helping analyze image contrast, brightness, and features. OpenCV provides functions to calculate and display histograms easily.
⚙️

How It Works

A histogram in OpenCV counts how many pixels in an image have each possible brightness or color value. Imagine sorting a box of colored beads by color and counting how many beads are in each color group. The histogram is like a bar chart showing these counts.

For a grayscale image, the histogram shows pixel counts for brightness levels from 0 (black) to 255 (white). For color images, histograms can be made for each color channel (red, green, blue) separately.

This helps us understand the image's overall brightness and contrast. For example, if most pixels are dark, the histogram bars will be tall near 0. If the image is bright, bars will be taller near 255.

💻

Example

This example shows how to calculate and display a grayscale histogram using OpenCV in Python.

python
import cv2
import numpy as np
from matplotlib import pyplot as plt

# Load image in grayscale
image = cv2.imread('sample.jpg', cv2.IMREAD_GRAYSCALE)

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

# Plot histogram
plt.plot(hist)
plt.title('Grayscale Histogram')
plt.xlabel('Pixel Intensity')
plt.ylabel('Number of Pixels')
plt.show()
Output
A plot window showing the grayscale histogram bars from pixel intensity 0 to 255.
🎯

When to Use

Histograms are useful when you want to analyze or improve images. For example:

  • Adjusting brightness and contrast by understanding pixel distribution.
  • Detecting if an image is too dark or too bright.
  • Comparing images by their color or brightness patterns.
  • Segmenting images by thresholding based on pixel intensity.
  • Enhancing images using histogram equalization to improve details.

In real life, histograms help in medical imaging, quality control in manufacturing, and photo editing apps.

Key Points

  • A histogram shows how pixel values are spread in an image.
  • OpenCV's calcHist function computes histograms efficiently.
  • Histograms help analyze image brightness, contrast, and color distribution.
  • They are useful for image enhancement and segmentation tasks.

Key Takeaways

A histogram in OpenCV counts pixels by brightness or color value to show image distribution.
Use OpenCV's calcHist function to compute histograms for grayscale or color images.
Histograms help analyze and improve image brightness, contrast, and color balance.
They are essential for tasks like image enhancement, thresholding, and segmentation.