How to plot histograms of different colors of an image in OpenCV Python?

To compute the histogram in OpenCV, we use the cv2.calcHist() function. In this tutorial, we will show how to compute and plot histograms for different color channels (Blue, Green, and Red) of an input image.

A histogram shows the distribution of pixel intensities in an image. For color images, we can create separate histograms for each color channel to analyze the color composition.

Understanding cv2.calcHist() Parameters

The cv2.calcHist() function takes the following parameters ?

  • images Source image as a list [img]
  • channels Channel index [0] for Blue, [1] for Green, [2] for Red
  • mask Mask image (None for full image)
  • histSize Number of bins [256] for 8-bit images
  • ranges Range of pixel values [0,256]

Method 1: Plotting Histograms in Separate Subplots

This approach creates three separate subplots for each color channel ?

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

# Create a sample colorful image for demonstration
img = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)

# Calculate histograms for Blue, Green, Red channels
hist_blue = cv2.calcHist([img], [0], None, [256], [0, 256])
hist_green = cv2.calcHist([img], [1], None, [256], [0, 256])
hist_red = cv2.calcHist([img], [2], None, [256], [0, 256])

# Plot histograms in separate subplots
plt.figure(figsize=(12, 8))

plt.subplot(3, 1, 1)
plt.plot(hist_blue, color='b')
plt.title('Blue Channel Histogram')
plt.xlim([0, 256])

plt.subplot(3, 1, 2)
plt.plot(hist_green, color='g')
plt.title('Green Channel Histogram')
plt.xlim([0, 256])

plt.subplot(3, 1, 3)
plt.plot(hist_red, color='r')
plt.title('Red Channel Histogram')
plt.xlim([0, 256])

plt.tight_layout()
plt.show()

Method 2: Plotting All Histograms in One Plot

This method overlays all three color histograms in a single plot for easy comparison ?

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

# Create a sample colorful image
img = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)

# Define colors for plotting
colors = ['b', 'g', 'r']
labels = ['Blue', 'Green', 'Red']

plt.figure(figsize=(10, 6))

# Calculate and plot histogram for each color channel
for i, color in enumerate(colors):
    hist = cv2.calcHist([img], [i], None, [256], [0, 256])
    plt.plot(hist, color=color, label=labels[i])

plt.title('Color Histograms')
plt.xlabel('Pixel Intensity')
plt.ylabel('Frequency')
plt.xlim([0, 256])
plt.legend()
plt.show()

Working with Real Images

When working with actual image files, replace the sample image creation with file reading ?

import cv2
import matplotlib.pyplot as plt

# Read an actual image file
img = cv2.imread('/path/to/your/image.jpg')

# Convert from BGR to RGB for proper color display
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Calculate histograms for each channel
colors = ['r', 'g', 'b']  # Note: OpenCV uses BGR format
labels = ['Red', 'Green', 'Blue']

plt.figure(figsize=(10, 6))

for i, color in enumerate(colors):
    hist = cv2.calcHist([img], [2-i], None, [256], [0, 256])  # Reverse order for BGR
    plt.plot(hist, color=color, label=labels[i])

plt.title('Image Color Histograms')
plt.xlabel('Pixel Intensity')
plt.ylabel('Frequency')
plt.xlim([0, 256])
plt.legend()
plt.show()

Comparison of Methods

Method Display Best For
Separate Subplots Individual analysis Detailed examination of each channel
Single Plot Overlaid comparison Quick comparison between channels

Conclusion

Use cv2.calcHist() to compute color histograms with different channel indices [0], [1], [2] for Blue, Green, Red. Choose separate subplots for detailed analysis or overlaid plots for quick comparison.

Updated on: 2026-03-26T21:59:22+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements