You are on page 1of 3

Q: - Write a Program in C that will

a. Read a grayscale image of any size.


b. Find the frequency of each grayscale.
c. Find the histogram of the image.

Code:
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
int main()
{
Mat image = imread("cameraman.png");
namedWindow("Input Image");
imshow("Input Image",image);
int Number_of_Pixels=0,r=0,c=0;
r=image.rows;
c=image.cols;
Number_of_Pixels=r*c;
cout<<"Total Number of Pixels="<<Number_of_Pixels<<endl;
// Allcoate memory for no of pixels for each intensity value
int histogram[256];
// Initialize all intensity values to 0
for(int i = 0; i < 255; i++)
{
histogram[i] = 0;
}
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
histogram[(int)image.at<uchar>(i,j)]++;
}
}
int sum=0;
// Calculate the no of pixels for each intensity values
for(int i = 0; i < 256; i++)
{
cout<<"["<<i<<"]="<<histogram[i]<<"\t";
sum=sum+histogram[i];
}
cout<<"Total Number of Pixels="<<sum<<"\t";
// Draw the histogram
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];
}
}
cout<<"Maximum Intensity="<<max;
// Normalize the histogram between 0 and histImage.rows

for(int i = 0; i < 255; i++){


histogram[i] = ((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);
}
// Display histogram
namedWindow("Intensity Histogram", CV_WINDOW_AUTOSIZE);
imshow("Intensity Histogram", histImage);
waitKey(0);
return 0;
}

Outputs
Frequency of each grayscale:

Histogram:

You might also like