Analyze an image using Histogram in OpenCV Python Programming
In this tutorial, we will learn to analyze an image on a histogram using matplotlib and OpenCV library in Python. OpenCV is an open-source library that supports programming languages like Python, Java, etc. Opencv is popular in image processing, video processing, object detection, etc. But first of all, let’s understand how do we analyze an image on a histogram.
Image analysis using OpenCV in Python
I assume that you are familiar with the matplotlib library used for visualization in Python.
So, let’s start…
importing the library first
import matplotlib.pyplot as plt import cv2
Before moving to the visualization let’s understand how each pixel is represented in an image. For this particular problem, we are going to use the Grayscale image where each pixel values are ranging from 0-255 and each pixel is intensity information of an image. In a Grayscale image 0 represents the lowest intensity that is black and 255 represents the brightest that is white. Thus the composed form of black and white is called a Grayscale image.
Now let’s understand Histogram. The histogram is the graph plot of the frequency of each pixel in an image. Thus each pixel is a sample for an image. Therefore histogram is used to quantify the number of pixels for each intensity value in an image.
Let’s see how can we perform this analysis using OpenCV.
Reading the image in Grayscale mode using OpenCV
img = cv2.imread('img.jpg',0)
OpenCV provides an in-built function for calculating the histogram and then plot it using matplotlib.
cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])
images – The source image is of type uint8 or float32.
channels – index of the channel.  for grayscale image and for color image  for blue,  for red and  for green.
mask – mask the image. It is None here.
histSize – this is the bin count or the number of bins for our analysis.
ranges – the range is from 0-256.
histr = cv2.calcHist([img],,None,,[0,256])
let’s plot it using matplotlib
An alternative way to do the same analysis is to read the image using OpenCV and plot the histogram using plot.hist() function by matplotlib library.