This blog shows how to get intensity histogram of an image.
Language: C++
Libraries: OpenCV
I use Eclipse to develop the code. If you are new to OpenCV and Eclipse, Please follow my previous blogs.
How to install OpenCV
https://sltechgeekx.blogspot.com/2022/06/how-to-installing-opencv-from-source.html
How to Create a Project in Eclipse with OpenCV Libraries
https://sltechgeekx.blogspot.com/2022/06/how-to-convert-rgb-image-to-gray.html
Program Source Code
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv)
{
char* ImageFile = argv[1];
Mat input_image; /* mat object for storing original_image */
input_image = imread( ImageFile, IMREAD_COLOR ); /* read ImageFile */
if( argc != 2 || !input_image.data )
{
printf( " No image data \n " );
return -1;
}
Mat gray_image; /* mat object for storing gray_image */
cvtColor( input_image, gray_image, COLOR_BGR2GRAY ); /* convert image from color to gray */
int histogram[256]; /* allcoate memory for no of pixels for each intensity value */
/* initialize all intensity values to 0 */
for(int i = 0; i < 255; i++)
{
histogram[i] = 0;
}
/* calculate the no of pixels for each intensity values */
for(int y = 0; y < gray_image.rows; y++)
{
for(int x = 0; x < gray_image.cols; x++)
{
histogram[(int)gray_image.at<uchar>(y,x)]++;
}
}
/* draw the histograms */
int hist_w = 512; int hist_h = 400;
int bin_w = cvRound((double) hist_w/256);
Mat histImage(hist_h, hist_w, CV_8UC1, Scalar(255, 255, 255));
/* find the maximum intensity element from histogram */
int max = histogram[0];
for(int i = 1; i < 256; i++)
{
if(max < histogram[i])
{
max = histogram[i];
}
}
/* normalize the histogram between 0 and histImage.rows */
for(int i = 0; i < 255; i++)
{
histogram[i] = floor(((double)histogram[i]/max)*histImage.rows);
}
/* draw the intensity line for histogram */
for(int i = 0; i < 255; i++)
{
line(histImage, Point(bin_w*(i), hist_h),
Point(bin_w*(i), hist_h - histogram[i]),
Scalar(0,0,0), 1, 8, 0);
}
namedWindow( "Input Image in Gray", WINDOW_AUTOSIZE ); /* set window name Gray Image */
imshow( "Input Image in Gray", gray_image ); /* show window containing gray_image */
namedWindow("Intensity Histogram", WINDOW_AUTOSIZE); /* set window name Intensity Histogram */
imshow("Intensity Histogram", histImage); /* show window containing Intensity Histogram */
waitKey(0); /* to exit */
return 0;
}
Program Output