OpenCV 5.0.0-pre
Open Source Computer Vision
|
Prev Tutorial: Histogram Equalization
Next Tutorial: Histogram Comparison
Original author | Ana Huamán |
Compatibility | OpenCV >= 3.0 |
In this tutorial you will learn how to:
What happens if we want to count this data in an organized way? Since we know that the range of information value for this case is 256 values, we can segment our range in subparts (called bins) like:
\[\begin{array}{l} [0, 255] = { [0, 15] \cup [16, 31] \cup ....\cup [240,255] } \\ range = { bin_{1} \cup bin_{2} \cup ....\cup bin_{n = 15} } \end{array}\]
and we can keep count of the number of pixels that fall in the range of each \(bin_{i}\). Applying this to the example above we get the image below ( axis x represents the bins and axis y the number of pixels in each of them).
For simple purposes, OpenCV implements the function cv::calcHist , which calculates the histogram of a set of arrays (usually images or image planes). It can operate with up to 32 dimensions. We will see it in the code below!
Load the source image
Separate the source image in its three R,G and B planes. For this we use the OpenCV function cv::split :
our input is the image to be divided (this case with three channels) and the output is a vector of Mat )
Establish the number of bins (5, 10...):
Set the range of values (as we said, between 0 and 255 )
We want our bins to have the same size (uniform) and to clear the histograms in the beginning, so:
We proceed to calculate the histograms by using the OpenCV function cv::calcHist :
Create an image to display the histograms:
Notice that before drawing, we first cv::normalize the histogram so its values fall in the range indicated by the parameters entered:
Observe that to access the bin (in this case in this 1D-Histogram):
we use the expression (C++ code):
where \(i\) indicates the dimension. If it were a 2D-histogram we would use something like:
Finally we display our histograms and wait for the user to exit: