Change language

OpenCV Python program to analyze an image using a histogram

| | | | |

This article discusses parsing images using Matplotlib and OpenCV. Let’s first understand how to experiment with image data in different styles and how to represent it using a histogram. 

Importing image data

 import matplotlib.pyplot as plt #importing matplotlib 

The image must be used in a PNG file as matplotlib only supports PNG images. Here it is the 24-bit RGB PNG image (8-bit for each of R, G, B) used in this example. Each inner list represents a pixel. Here with the RGB image, there are 3 values. For RGB images, matplotlib supports the float32 and uint8 datatypes.

 img = plt.imread (’flower.png’) #reads image data 

In Matplotlib, this is done with the imshow () function. Here we grabbed the plot object.

Everything about the histogram

The histogram is viewed as a graph or graph that is related to frequency pixels in a gray scale image. 
with pixel values ​​(0 to 255). Grayscale image — it is an image in which the value of each pixel is a single sample, that is, it only carries information about the intensity, where the pixel value varies from 0 to 255. Images of this type, also known as black and white, are compiled. exclusively grayscale, from blacks at the lowest intensity to whites at the strongest, where a pixel can be thought of as every point in the image. 
What the GrayScale image looks like:

It quantifies the number of pixels for each intensity value considered. Before moving on to the histogram, let’s get a rough idea of ​​this example. 

Here we get an intuition about contrast, brightness, intensity distribution and T. D. This image. As we can see the image and its histogram, which is drawn for a grayscale image, not a color image. 
The left area of ​​the histogram shows the number of darker pixels in the image, and the right area shows the number of brighter pixels.

Create a histogram using the numpy array

To create a histogram of our image data, we use the hist () function.

 plt.hist (n_img.ravel (), bins = 256, range = (0.0, 1.0), fc = ’k’, ec =’ k’) #calculating histogram 

In our histogram, this looks like the distribution of intensity over the entire image. Black and white pixels as grayscale images.

From the histogram we can infer that the dark area — this is more than a bright area.

Now we are dealing with an image, which consists of a pixel intensity distribution where the pixel value changes. First, we need to calculate the histogram using the built-in OpenCV function.

Calculate the histogram

Here we use cv2 .calcHist () (built-in function in OpenCV) to find the histogram.

 cv2.calcHist (images, channels, mask, histSize, ranges [, hist [, accumulate]] ) 

images: this is the original uint8 or float32 image represented as "[img]". 
channels: is the channel index for which we are calculating the histogram. For a grayscale image, its value is [0] and
Color image, you can send [0], [1] or [2] to calculate the histogram of the blue, green, or red channel respectively. 
mask: image mask. To find the full image histogram, it is listed as “None”. 
histSize: this represents our BIN counter. For full scale, we transmit [256]. 
Ranges : this is our RANGE. This is usually [0,256].

For example:

# load grayscale image

img = cv2.imread ( ’ex.jpg’ , 0 )

# calculate pixel frequency in the range 0-255

histg = cv2.calcHist ([img], [ 0 ], None , [ 256 ], [ 0 , 256 ]) 

Then we need to plot a histogram to show the characteristics of the image.

Plotting histograms

Analysis using Matplotlib:

# import required libraries opencv

import cv2

# import drawing library

from matplotlib import pyplot as plt

# reads input image

img = cv2.imread ( ’ex.jpg’ , 0 )

# find pixel frequency in the range 0-255

histr = cv2.calcHist ([img], [ 0 ], None , [ 256 ], [ 0 , 256 ])

# show a graphic image of the image
plt.plot (histr) ()

Input data:


The illustration shows that each number of pixels in the image ranges from 0 to 255. In the second example, it finds the histogram directly and plots it. We don’t need to use calcHist (). See the code below:

< / tr>

import cv2

from matplotlib import pyplot as plt

img = cv2.imread ( ’ex.jpg’ , 0 )

# an alternative way to find the image histogram

plt.hist (img.ravel (), 256 , [ 0 , 256 ]) ()


Thus, we conclude that the image can be represented as a histogram to understand the idea of ​​intensity distribution over the image and further calm it.


  • imgproc

This article courtesy of Afzal Ansari . If you are as Python.Engineering and would like to contribute, you can also write an article using or by posting the article [email protected] ... See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.


Learn programming in R: courses


Best Python online courses for 2022


Best laptop for Fortnite


Best laptop for Excel


Best laptop for Solidworks


Best laptop for Roblox


Best computer for crypto mining


Best laptop for Sims 4


Latest questions


psycopg2: insert multiple rows with one query

12 answers


How to convert Nonetype to int or string?

12 answers


How to specify multiple return types using type-hints

12 answers


Javascript Error: IPython is not defined in JupyterLab

12 answers



Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method