Image Processing — Histogram Calculation: Part 3
First of all, we need to know about “what is a histogram ?”, Then we will deal with the calculation part.
What is Histogram?
The histogram is a graph showing the number of pixels in an image at each different intensity value found in that image.
How does It work?
This is a simple process. The image is scanned in a single pass and a running count of the number of pixels found at each intensity value is kept. By using this information, a relevant histogram can be constructed.
Next, I’ll focus on:
- Calculate histograms, using both OpenCV and Numpy functions.
- Plot histograms, using OpenCV and Matplotlib functions
- Apply mask operations on histograms
Calculate Histograms
Calculate Histogram : Gives useful information to analyze the properties of images.
1. Using OpenCV
- We use the calcHist() function to find the histogram in OpenCV.
Input image :
Output histogram:
Note:
- Value = 0 — read image in gray scale mode
- Value > 0 — Color mode (BGR)
- Value < 0 — Binary image
Find frequency in pixels in the range 0–255
- [img]- source image; it is the source image of type uint8 or float32.
- [0]- channel, index of the channel which we calculate the histogram [0-gray scale]
- [None] — mask image. To find a histogram of the full image
- [256] — full scale/ bin count / histogram size
- [0,256] — normal range
2. Using Numpy functions
Numpy also provides a function, np.histogram() instead of calcHist() function.
Output histogram:
Note : numpy.ravel() in Python
Python numpy module provides a function called numpy.ravel. It is used to change a 2-dimensional array or a multi-dimensional array into a contiguous flattened array. It returns the same type of array as the source array.
Plotting Histograms
There are two ways of plotting,
- Matplotlib plotting functions
- OpenCV drawing functions
1. Using Matplotlib: BGR histograms
Input image:
Output histogram:
2. Using OpenCV
Using OpenCV, we can generate the histogram values along with their bin values. (like x,y coordinates)
Once this is done, use cv.line() or cv.polyline() function to generate same image as above.
Application of a mask
Earlier we learned about how to find the histogram of the full image.
What is the best way to get the histograms for specific regions of an image?
Solution: Creating a mask image.
How it is done?
Simply, make white color on the region where you want to find the histogram and make black on the rest. Then this will be the mask.
Let’s see the code now:
And…That’s it for now.
Note: Here I’ve attached an image file for your convenience.
This article is part of a series and my next article is regarding: Histogram Equalization.
If you enjoyed this piece, please hit the clap button 👏
See you guys in the next article! ❤️ ✌