demhist.cpp 2.4 KB

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