Histograms for Color Images

OpenCV's calcHist() function computes histograms at the channel level. For color images, we need to split the image into it's channels and compute the histograms for each respective channel. Here is an example of how to perform this operation.

Reading a sample image

import cv2
import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline
%config InlineBackend.figure_format = 'retina'
car_img = cv2.imread('car.jpg')
car_img = cv2.cvtColor(car_img, cv2.COLOR_BGR2RGB)

plt.figure(figsize=(8,5))
plt.imshow(car_img)
plt.tight_layout()
Computing Histogram for Color Images
car_img.shape
(2880, 1920, 3)

The image has 3 channels in the BGB format. The function below returns the histograms for each channel

def compute_hist(img, channel, bins, intensity_range):
    return cv2.calcHist([img], [channel], None, [bins], intensity_range)
r_hist = compute_hist(car_img, 0, 256, [0, 256])
        g_hist = compute_hist(car_img, 1, 256, [0, 256])
        b_hist = compute_hist(car_img, 2, 256, [0, 256])

Visualizing the histogram

# plotting the histogram
fig = plt.figure(figsize=(12, 7))
plt.plot(b_hist, color='b', label='BLUE')
plt.plot(g_hist, color='g', label='GREEN')
plt.plot(r_hist, color='r', label='RED')

plt.title('Histogram of Color Car Image')
plt.xlabel('Pixel Intensity')
plt.ylabel('# of pixels on image')
plt.legend()
Historgram for Color Images

Notice that all channels have higher density on the lower pixel intensity values which points to the fact that the image is largely composed of dark colors.