opencv/samples/cpp/demhist.cpp

99 lines
2.5 KiB
C++
Raw Normal View History

#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
2014-07-04 22:48:15 +08:00
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
2010-11-28 07:15:16 +08:00
#include <iostream>
using namespace cv;
using namespace std;
int _brightness = 100;
int _contrast = 100;
Mat image;
/* brightness/contrast callback function */
2012-06-08 01:21:29 +08:00
static void updateBrightnessContrast( int /*arg*/, void* )
2010-11-28 07:15:16 +08:00
{
int histSize = 64;
int brightness = _brightness - 100;
int contrast = _contrast - 100;
/*
* The algorithm is by Werner D. Streidt
* (http://visca.com/ffactory/archives/5-99/msg00021.html)
*/
double a, b;
if( contrast > 0 )
{
double delta = 127.*contrast/100;
a = 255./(255. - delta*2);
b = a*(brightness - delta);
}
else
{
double delta = -128.*contrast/100;
a = (256.-delta*2)/255.;
b = a*brightness + delta;
}
Mat dst, hist;
image.convertTo(dst, CV_8U, a, b);
imshow("image", dst);
calcHist(&dst, 1, 0, Mat(), hist, 1, &histSize, 0);
Mat histImage = Mat::ones(200, 320, CV_8U)*255;
2012-06-08 01:21:29 +08:00
normalize(hist, hist, 0, histImage.rows, NORM_MINMAX, CV_32F);
2010-11-28 07:15:16 +08:00
histImage = Scalar::all(255);
int binW = cvRound((double)histImage.cols/histSize);
for( int i = 0; i < histSize; i++ )
rectangle( histImage, Point(i*binW, histImage.rows),
Point((i+1)*binW, histImage.rows - cvRound(hist.at<float>(i))),
Scalar::all(0), -1, 8, 0 );
imshow("histogram", histImage);
}
2012-06-08 01:21:29 +08:00
static void help()
2010-12-03 18:21:55 +08:00
{
2012-06-08 01:21:29 +08:00
std::cout << "\nThis program demonstrates the use of calcHist() -- histogram creation.\n"
2018-10-31 20:48:56 +08:00
<< "Usage: \n" << "demhist [image_name -- Defaults to baboon.jpg]" << std::endl;
2010-12-03 18:21:55 +08:00
}
2010-11-28 07:15:16 +08:00
2012-06-08 01:21:29 +08:00
const char* keys =
2010-11-28 07:15:16 +08:00
{
2018-10-31 20:48:56 +08:00
"{help h||}{@image|baboon.jpg|input image file}"
2011-08-10 20:33:03 +08:00
};
int main( int argc, const char** argv )
{
2012-06-08 01:21:29 +08:00
CommandLineParser parser(argc, argv, keys);
2015-08-01 23:24:23 +08:00
if (parser.has("help"))
{
help();
return 0;
}
2013-01-31 16:08:43 +08:00
string inputImage = parser.get<string>(0);
2012-06-08 01:21:29 +08:00
// Load the source image. HighGUI use.
2018-10-31 20:48:56 +08:00
image = imread(samples::findFile(inputImage), IMREAD_GRAYSCALE);
2012-06-08 01:21:29 +08:00
if(image.empty())
{
std::cerr << "Cannot read image file: " << inputImage << std::endl;
return -1;
}
2010-11-28 07:15:16 +08:00
namedWindow("image", 0);
namedWindow("histogram", 0);
createTrackbar("brightness", "image", &_brightness, 200, updateBrightnessContrast);
createTrackbar("contrast", "image", &_contrast, 200, updateBrightnessContrast);
updateBrightnessContrast(0, 0);
waitKey();
return 0;
}