0
0
Computer Visionml~5 mins

Histogram computation in Computer Vision

Choose your learning style9 modes available
Introduction

A histogram helps us see how often different colors or brightness levels appear in an image. It shows the picture's color or light distribution in a simple graph.

To understand the brightness levels in a photo before editing it.
To compare two images by their color or brightness patterns.
To improve image quality by adjusting contrast based on the histogram.
To detect if an image is too dark or too bright automatically.
To prepare images for machine learning by analyzing pixel distributions.
Syntax
Computer Vision
cv2.calcHist(images, channels, mask, histSize, ranges)

# images: list of images (usually one image in a list)
# channels: list of channel indices (e.g., [0] for grayscale or blue channel)
# mask: None or mask image to select part of image
# histSize: list with number of bins (e.g., [256])
# ranges: list with pixel value range (e.g., [0, 256])

The function returns a histogram array showing counts of pixels in each bin.

For color images, you can compute histograms for each color channel separately.

Examples
Compute histogram of a grayscale image for pixel values 0 to 255.
Computer Vision
hist = cv2.calcHist([image], [0], None, [256], [0, 256])
Compute histograms for blue, green, and red channels of a color image.
Computer Vision
hist_b = cv2.calcHist([image], [0], None, [256], [0, 256])
hist_g = cv2.calcHist([image], [1], None, [256], [0, 256])
hist_r = cv2.calcHist([image], [2], None, [256], [0, 256])
Sample Model

This code creates a small grayscale image with pixel values 50, 100, 150, and 200 repeated. It computes the histogram and prints how many pixels have each value.

Computer Vision
import cv2
import numpy as np

# Create a simple grayscale image with two pixel values
image = np.array([[50, 50, 100, 100],
                  [50, 50, 100, 100],
                  [150, 150, 200, 200],
                  [150, 150, 200, 200]], dtype=np.uint8)

# Compute histogram with 256 bins for pixel values 0-255
hist = cv2.calcHist([image], [0], None, [256], [0, 256])

# Print histogram values for bins with counts
for i, val in enumerate(hist):
    if val[0] > 0:
        print(f"Pixel value {i}: {int(val[0])} pixels")
OutputSuccess
Important Notes

Histograms are useful to understand image brightness and color distribution quickly.

Using a mask lets you compute histograms for only part of the image.

Bins group pixel values; more bins mean finer detail but more data.

Summary

A histogram counts how many pixels fall into each brightness or color range.

It helps us see if an image is dark, bright, or balanced.

OpenCV's calcHist function makes it easy to compute histograms.