Image histogram

A histogram is collected counts of data organized into a set of bins. Every bin shows the frequency. OpenCV can generate histograms for both color and gray scale images. You may want to use histograms for computer vision tasks.

Related course
Introduction to Computer Vision Master OpenCV in Python

Histogram example
Given an image we can generate a histogram for the blue, green and red values.

Histogram Calculation

We use the function cv.CalcHist(image, channel, mask, histSize, range)


  • image:  should be in brackets,  the source image of type uint8 or float32
  • channel:  the color channel to select. for grayscale use [0]. color image has blue, green and red channels
  • mask:  None if you want a histogram of the full image, otherwise a region.
  • histSize:  the number of bins
  • range:  color range:

Histogram for a color image:

# draw histogram in python. 
import cv2
import numpy as np
img = cv2.imread('image.jpg')
h = np.zeros((300,256,3))
bins = np.arange(256).reshape(256,1)
color = [ (255,0,0),(0,255,0),(0,0,255) ]
for ch, col in enumerate(color):
    hist_item = cv2.calcHist([img],[ch],None,[256],[0,255])
    pts = np.column_stack((bins,hist))