BasicLinearTransforms.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * @file BasicLinearTransforms.cpp
  3. * @brief Simple program to change contrast and brightness
  4. * @author OpenCV team
  5. */
  6. #include "opencv2/imgcodecs.hpp"
  7. #include "opencv2/highgui.hpp"
  8. #include <iostream>
  9. // we're NOT "using namespace std;" here, to avoid collisions between the beta variable and std::beta in c++17
  10. using std::cin;
  11. using std::cout;
  12. using std::endl;
  13. using namespace cv;
  14. /**
  15. * @function main
  16. * @brief Main function
  17. */
  18. int main( int argc, char** argv )
  19. {
  20. /// Read image given by user
  21. //! [basic-linear-transform-load]
  22. CommandLineParser parser( argc, argv, "{@input | lena.jpg | input image}" );
  23. Mat image = imread( samples::findFile( parser.get<String>( "@input" ) ) );
  24. if( image.empty() )
  25. {
  26. cout << "Could not open or find the image!\n" << endl;
  27. cout << "Usage: " << argv[0] << " <Input image>" << endl;
  28. return -1;
  29. }
  30. //! [basic-linear-transform-load]
  31. //! [basic-linear-transform-output]
  32. Mat new_image = Mat::zeros( image.size(), image.type() );
  33. //! [basic-linear-transform-output]
  34. //! [basic-linear-transform-parameters]
  35. double alpha = 1.0; /*< Simple contrast control */
  36. int beta = 0; /*< Simple brightness control */
  37. /// Initialize values
  38. cout << " Basic Linear Transforms " << endl;
  39. cout << "-------------------------" << endl;
  40. cout << "* Enter the alpha value [1.0-3.0]: "; cin >> alpha;
  41. cout << "* Enter the beta value [0-100]: "; cin >> beta;
  42. //! [basic-linear-transform-parameters]
  43. /// Do the operation new_image(i,j) = alpha*image(i,j) + beta
  44. /// Instead of these 'for' loops we could have used simply:
  45. /// image.convertTo(new_image, -1, alpha, beta);
  46. /// but we wanted to show you how to access the pixels :)
  47. //! [basic-linear-transform-operation]
  48. for( int y = 0; y < image.rows; y++ ) {
  49. for( int x = 0; x < image.cols; x++ ) {
  50. for( int c = 0; c < image.channels(); c++ ) {
  51. new_image.at<Vec3b>(y,x)[c] =
  52. saturate_cast<uchar>( alpha*image.at<Vec3b>(y,x)[c] + beta );
  53. }
  54. }
  55. }
  56. //! [basic-linear-transform-operation]
  57. //! [basic-linear-transform-display]
  58. /// Show stuff
  59. imshow("Original Image", image);
  60. imshow("New Image", new_image);
  61. /// Wait until the user press a key
  62. waitKey();
  63. //! [basic-linear-transform-display]
  64. return 0;
  65. }