1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
/**
* Code sample for displaying image histogram in OpenCV.
*/
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
void showHistogram(Mat& img)
{
int bins = 256; // number of bins
int nc = img.channels(); // number of channels
vector<Mat> hist(nc); // histogram arrays
// Initalize histogram arrays
for (int i = 0; i < hist.size(); i++)
hist[i] = Mat::zeros(1, bins, CV_32SC1);
// Calculate the histogram of the image
for (int i = 0; i < img.rows; i++)
{
for (int j = 0; j < img.cols; j++)
{
for (int k = 0; k < nc; k++)
{
uchar val = nc == 1 ? img.at<uchar>(i,j) : img.at<Vec3b>(i,j)[k];
hist[k].at<int>(val) += 1;
}
}
}
// For each histogram arrays, obtain the maximum (peak) value
// Needed to normalize the display later
int hmax[3] = {0,0,0};
for (int i = 0; i < nc; i++)
{
for (int j = 0; j < bins-1; j++)
hmax[i] = hist[i].at<int>(j) > hmax[i] ? hist[i].at<int>(j) : hmax[i];
}
const char* wname[3] = { "blue", "green", "red" };
Scalar colors[3] = { Scalar(255,0,0), Scalar(0,255,0), Scalar(0,0,255) };
vector<Mat> canvas(nc);
// Display each histogram in a canvas
for (int i = 0; i < nc; i++)
{
canvas[i] = Mat::ones(125, bins, CV_8UC3);
for (int j = 0, rows = canvas[i].rows; j < bins-1; j++)
{
line(
canvas[i],
Point(j, rows),
Point(j, rows - (hist[i].at<int>(j) * rows/hmax[i])),
nc == 1 ? Scalar(200,200,200) : colors[i],
1, 8, 0
);
}
imshow(nc == 1 ? "value" : wname[i], canvas[i]);
}
}
// Test the `showHistogram()` function above
int main()
{
Mat src = imread("c:/users/nash/desktop/assets/lena.jpg");
if (src.empty())
return -1;
showHistogram(src);
imshow("src", src);
waitKey(0);
return 0;
}
|