The Wayback Machine - https://web.archive.org/web/20240930180855/https://www.geeksforgeeks.org/opencv-python-program-analyze-image-using-histogram/
Open In App

OpenCV Python Program to analyze an image using Histogram

Last Updated : 06 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, image analysis using Matplotlib and OpenCV is discussed. Let’s first understand how to experiment image data with various styles and how to represent with Histogram. Prerequisites:

Importing image data

import matplotlib.pyplot as plt #importing matplotlib

The image should be used in a PNG file as matplotlib supports only PNG images. Here, It’s a 24-bit RGB PNG image (8 bits for each of R, G, B) used in this example. Each inner list represents a pixel. Here, with an RGB image, there are 3 values. For RGB images, matplotlib supports float32 and uint8 data types.

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

In Matplotlib, this is performed using the

imshow()

function. Here we have grabbed the plot object.

All about Histogram

Histogram is considered as a graph or plot which is related to frequency of pixels in an Gray Scale Image with pixel values (ranging from 0 to 255). Grayscale image is an image in which the value of each pixel is a single sample, that is, it carries only intensity information where pixel value varies from 0 to 255. Images of this sort, also known as black-and-white, are composed exclusively of shades of gray, varying from black at the weakest intensity to white at the strongest where Pixel can be considered as a every point in an image. How GrayScale Image looks like:

images

It quantifies the number of pixels for each intensity value considered. Before going through Histogram, lets have a rough idea from this given example.

histogram_sample

Here, we get intuition about contrast, brightness, intensity distribution etc of that image. As we can see the image and its histogram which is drawn for grayscale image, not color image. Left region of histogram shows the amount of darker pixels in image and right region shows the amount of brighter pixels.

Histogram creation using 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
c1

In our histogram, it looks like there’s distribution of intensity all over image Black and White pixels as grayscale image. From the histogram, we can conclude that dark region is more than brighter region. Now, we will deal with an image which  consist of intensity distribution of pixels where pixel value varies. First, we need to calculate histogram using OpenCV in-built function.

Histogram Calculation

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

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

images :

it is the source image of type uint8 or float32 represented as “[img]”.

channels :

it is the index of channel for which we calculate histogram. For grayscale image, its value is [0] and color image, you can pass [0], [1] or [2] to calculate histogram of blue, green or red channel respectively.

mask :

mask image. To find histogram of full image, it is given as “None”.

histSize :

this represents our BIN count. For full scale, we pass [256].

ranges

: this is our RANGE. Normally, it is [0,256]. For example:

Python
# load an image in grayscale mode
img = cv2.imread('ex.jpg',0)

# calculate frequency of pixels in range 0-255
histg = cv2.calcHist([img],[0],None,[256],[0,256]) 

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

Plotting Histograms

Analysis using Matplotlib:

Python
# importing required libraries of opencv
import cv2

# importing library for plotting
from matplotlib import pyplot as plt

# reads an input image
img = cv2.imread('ex.jpg',0)

# find frequency of pixels in range 0-255
histr = cv2.calcHist([img],[0],None,[256],[0,256])

# show the plotting graph of an image
plt.plot(histr)
plt.show()

Input:

nature2nature3nature4

Output:

n2n3n4

Illustration shows that each number of pixels of an image lie upon range of 0 to 255. In the second example, it directly finds the histogram and plot it. We need not use calcHist(). See the code below:

Python
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('ex.jpg',0)

# alternative way to find histogram of an image
plt.hist(img.ravel(),256,[0,256])
plt.show()

Output:

f1

Thus, we conclude that image can be represented as a Histogram to conceive the idea of intensity distribution over an image and further its tranquility.

References:

  • http://docs.opencv.org/2.4/doc/tutorials/imgproc/table_of_content_imgproc/table_of_content_imgproc.html#table-of-content-imgproc
  • http://www.cambridgeincolour.com/tutorials/histograms1.htm


Previous Article
Next Article

Similar Reads

Histogram matching with OpenCV, scikit-image, and Python
Histogram matching is used for normalizing the representation of images, it can be used for feature matching, especially when the pictures are from diverse sources or under varied conditions (depending on the light, etc). each image has a number of channels, each channel is matched individually. Histogram matching is possible only if the number of
3 min read
CLAHE Histogram Equalization - OpenCV
In this tutorial, we are going to learn how to apply CLAHE and process a given input image for histogram equalization. In this tutorial, we are going to see how to apply Contrast Limited Adaptive Histogram Equalization (CLAHE) to equalize images. CLAHE is a variant of Adaptive histogram equalization (AHE) which takes care of over-amplification of t
2 min read
Convert OpenCV image to PIL image in Python
OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. When it is integrated with various libraries, such as Numpy which is a
3 min read
OpenCV - Facial Landmarks and Face Detection using dlib and OpenCV
Content has been removed on Author's request.
1 min read
Python PIL | Image.histogram()
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.Image.histogram() Return
4 min read
Transition from OpenCV 2 to OpenCV 3.x
OpenCV is one of the most popular and most used Computer vision libraries. It contains tools to carry out image and video processing. When OpenCV 3..4.1 is an improved version of OpenCV 2.4 as it introduced new algorithms and features. Although some of the existing modules were rewritten and moved to sub-modules. In this articles, I will focus on t
2 min read
Top Books for Learning OpenCV: Computer Vision with OpenCV Library
OpenCV or Open Source Computer Vision Library, is an open-source computer vision and machine learning software library. It's extensively used for real-time computer vision tasks such as object detection, face recognition, image processing, etc. Whether you're a beginner or an experienced developer looking to deepen your understanding of OpenCV, her
5 min read
Image resizing using Seam carving using OpenCV in Python
Seam carving is an effective image processing technique with the help of which an image can be resized without removing important elements from the image. The basic approach is to find all the continuous pixels with low energy from left to right or from top to bottom. After the region is selected, it is removed from the original image, leaving only
2 min read
Mahotas – Full Histogram of Image
In this article we will see how we can histogram of the image in mahotas. An image histogram is a type of histogram that acts as a graphical representation of the tonal distribution in a digital image. It plots the number of pixels for each tonal value. By looking at the histogram for a specific image a viewer will be able to judge the entire tonal
2 min read
PyQtGraph – Getting Histogram Object for Image View
In this article, we will see how we can get the histogram object of the image view object in PyQTGraph. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.
4 min read
Python | OpenCV program to read and save an Image
OpenCV (Open Source Computer Vision) is a library of programming functions mainly aimed at real-time computer vision. This is cross-platform library, it provides functions that are used in multiple languages. Coming to image processing, OpenCV enables us to perform multiple operations on image, but in order to do that we need to read an image file
2 min read
OpenCV Python Program to blur an image
Note: This post contains codes that cannot be run using an online compiler. Please make sure that you have Python 2.7 and cv2 module installed before trying to run the program on your system. Hi everyone! I read a brilliant work by Aditya Prakash – OpenCV C++ Program to blur an image, so I decided to come up with something similar but this time in
2 min read
Find the Solidity and Equivalent Diameter of an Image Object Using OpenCV Python
In this article, we will see how we can find the solidity and the equivalent diameter of an object present in an image with help of Python OpenCV. Function to Find Solidity The solidity of an image is the measurement of the overall concavity of a particle. We can define the solidity of an object as the ratio of the contour area to its convex hull a
4 min read
Python | Detect corner of an image using OpenCV
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos. Let's see how to detect the corner in the image. cv2.goodFeaturesToTrack() method finds N strongest corners in the image by Shi-Tomasi metho
2 min read
Image Pyramid using OpenCV | Python
Image Pyramids are one of the most beautiful concept of image processing.Normally, we work with images with default resolution but many times we need to change the resolution (lower it) or resize the original image in that case image pyramids comes handy. The pyrUp() function increases the size to double of its original size and pyrDown() function
1 min read
Negative transformation of an image using Python and OpenCV
Image is also known as a set of pixels. When we store an image in computers or digitally, it’s corresponding pixel values are stored. So, when we read an image to a variable using OpenCV in Python, the variable stores the pixel values of the image. When we try to negatively transform an image, the brightest areas are transformed into the darkest an
4 min read
Python | Image blurring using OpenCV
Image Blurring refers to making the image less clear or distinct. It is done with the help of various low pass filter kernels. Advantages of blurring: It helps in Noise removal. As noise is considered as high pass signal so by the application of low pass filter kernel we restrict noise. It helps in smoothing the image. Low intensity edges are remov
2 min read
Find Circles and Ellipses in an Image using OpenCV | Python
To identify circles, ellipses, or in general, any shape in which the pixels are connected we use the SimpleBlobDetector() function of OpenCV. In non-technical terms, a blob is understood as a thick liquid drop. Here, we are going to call all shapes a blob. Our task is to detect and recognize whether the blob is a circle or not. OpenCV provides a co
2 min read
Image Translation using OpenCV | Python
Translation refers to the rectilinear shift of an object i.e. an image from one location to another. If we know the amount of shift in horizontal and the vertical direction, say (tx, ty) then we can make a transformation matrix e.g. [Tex] \begin{bmatrix} 1 & 0 & tx \\ 0 & 1 & ty \end{bmatrix} [/Tex] where tx denotes the shift along
2 min read
Python | Detect Polygons in an Image using OpenCV
Approach : The approach we would be used to detect the shape of a given polygon will be based on classifying the detected shape on the basis of a number of sides it has. For example, if the detected polynomial has 3 sides, then it could be considered as a triangle, if the polynomial has 4 sides then it could be classified as a square or a rectangle
2 min read
Image Steganography using OpenCV in Python
Image Steganography is the process of hiding secret data in some image. In this post, we will hide one image inside another and convert it into another image and then extract back both the images from the previous image. The idea behind image-based Steganography is very simple. Images are composed of digital data (pixels), which describes what’s in
3 min read
Create Local Binary Pattern of an image using OpenCV-Python
In this article, we will discuss the image and how to find a binary pattern using the pixel value of the image. As we all know, image is also known as a set of pixels. When we store an image in computers or digitally, it’s corresponding pixel values are stored. So, when we read an image to a variable using OpenCV in Python, the variable stores the
5 min read
Log transformation of an image using Python and OpenCV
Logarithm value of a number is a number that raises power to a base number which gives the same number as in input. Simply, the logarithm is the inversion of exponential value of a number. log(exp(x)) = x How log value of a number is calculated? Let's see an example, [Tex]2^3 = 8[/Tex] By applying logarithm in both sides, log(2^3) = log(8) 3 * log(
3 min read
Point Processing in Image Processing using Python-OpenCV
OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. Point processing in spatial domain All the
3 min read
Set Countdown timer to Capture Image using Python-OpenCV
Prerequisites: Introduction to OpenCV Most of us have already captured image using countdown timer with our phones. We can do the same thing on our computer with the help of OpenCV. But here we can specify the countdown timer instead of choosing one of the specified countdown and whenever the particular key will be pressed (let’s say q) the countdo
3 min read
Displaying the coordinates of the points clicked on the image using Python-OpenCV
OpenCV helps us to control and manage different types of mouse events and gives us the flexibility to operate them. There are many types of mouse events. These events can be displayed by running the following code segment : import cv2 [print(i) for i in dir(cv2) if 'EVENT' in i] Output : EVENT_FLAG_ALTKEY EVENT_FLAG_CTRLKEY EVENT_FLAG_LBUTTON EVENT
3 min read
Rotate image without cutting off sides using Python - OpenCV
Prerequisite: Image Processing in Python (Scaling, Rotating, Shifting and Edge Detection) Rotating images with OpenCV is easy, but sometimes simple rotation tasks cropped/cut sides of an image, which leads to a half image. Now, In this tutorial, We will explore a solution to safely rotate an image without cropping/cutting sides of an image so that
6 min read
Check if the image is empty using Python - OpenCV
Prerequisite: Basics of OpenCV OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on pictures or videos. It was originally developed by Intel but was later maintained by Willow Garage and is now maintained by Itseez. This library is cross-platform that it is available in multiple
2 min read
Changing the contrast and brightness of an image using Python - OpenCV
Changing the Brightness and Contrast level of any image is the most basic thing everyone does with an image. It is meant to change the value of each and every pixel of an image it can be done by either multiplying or dividing the pixels value of an image. In this article, we will see how we can implement our theory in a beautiful code using OpenCV
6 min read
Draw Multiple Rectangles in Image using Python-Opencv
In this article, we are going to see how to draw multiple rectangles in an image using Python and OpenCV. Function used:imread(): In the OpenCV, the cv2.imread() function is used to read an image in Python. Syntax: cv2.imread(path_of_image, flag) rectangle(): In the OpenCV, the cv2.rectangle function is used to draw a rectangle on the image in Pyth
2 min read
Article Tags :
Practice Tags :