samples/cpp/demhist.cpp#
An example for creating histograms of an image
1#include "opencv2/core/utility.hpp"
2#include "opencv2/imgproc.hpp"
3#include "opencv2/imgcodecs.hpp"
4#include "opencv2/highgui.hpp"
5
6#include <iostream>
7
8using namespace cv;
9using namespace std;
10
11int _brightness = 100;
12int _contrast = 100;
13
14Mat image;
15
16/* brightness/contrast callback function */
17static void updateBrightnessContrast( int /*arg*/, void* )
18{
19 int histSize = 64;
20 int brightness = _brightness - 100;
21 int contrast = _contrast - 100;
22
23 /*
24 * The algorithm is by Werner D. Streidt
25 * (http://visca.com/ffactory/archives/5-99/msg00021.html)
26 */
27 double a, b;
28 if( contrast > 0 )
29 {
30 double delta = 127.*contrast/100;
31 a = 255./(255. - delta*2);
32 b = a*(brightness - delta);
33 }
34 else
35 {
36 double delta = -128.*contrast/100;
37 a = (256.-delta*2)/255.;
38 b = a*brightness + delta;
39 }
40
41 Mat dst, hist;
42 image.convertTo(dst, CV_8U, a, b);
43 imshow("image", dst);
44
45 calcHist(&dst, 1, 0, Mat(), hist, 1, &histSize, 0);
46 Mat histImage = Mat::ones(200, 320, CV_8U)*255;
47
48 normalize(hist, hist, 0, histImage.rows, NORM_MINMAX, CV_32F);
49
50 histImage = Scalar::all(255);
51 int binW = cvRound((double)histImage.cols/histSize);
52
53 for( int i = 0; i < histSize; i++ )
54 rectangle( histImage, Point(i*binW, histImage.rows),
55 Point((i+1)*binW, histImage.rows - cvRound(hist.at<float>(i))),
56 Scalar::all(0), -1, 8, 0 );
57 imshow("histogram", histImage);
58}
59
60const char* keys =
61{
62 "{help h||}{@image|baboon.jpg|input image file}"
63};
64
65int main( int argc, const char** argv )
66{
67 CommandLineParser parser(argc, argv, keys);
68 parser.about("\nThis program demonstrates the use of calcHist() -- histogram creation.\n");
69 if (parser.has("help"))
70 {
71 parser.printMessage();
72 return 0;
73 }
74 string inputImage = parser.get<string>(0);
75
76 // Load the source image. HighGUI use.
77 image = imread(samples::findFile(inputImage), IMREAD_GRAYSCALE);
78 if(image.empty())
79 {
80 std::cerr << "Cannot read image file: " << inputImage << std::endl;
81 return -1;
82 }
83
84 namedWindow("image", 0);
85 namedWindow("histogram", 0);
86
87 createTrackbar("brightness", "image", &_brightness, 200, updateBrightnessContrast);
88 createTrackbar("contrast", "image", &_contrast, 200, updateBrightnessContrast);
89
90 updateBrightnessContrast(0, 0);
91 waitKey();
92
93 return 0;
94}