当前位置:   article > 正文

[C++][opencv]基于opencv实现photoshop算法亮度和对比度调整

[C++][opencv]基于opencv实现photoshop算法亮度和对比度调整

【测试环境】

vs2019

opencv==4.8.0

【效果演示】

【核心实现代码】

  1. #include <iostream>
  2. #include "opencv2/core.hpp"
  3. #include "opencv2/imgproc.hpp"
  4. #include "opencv2/highgui.hpp"
  5. using namespace std;
  6. using namespace cv;
  7. #define SWAP(a, b, t) do { t = a; a = b; b = t; } while(0)
  8. #define CLIP_RANGE(value, min, max) ( (value) > (max) ? (max) : (((value) < (min)) ? (min) : (value)) )
  9. #define COLOR_RANGE(value) CLIP_RANGE(value, 0, 255)
  10. #define M_PI 3.14
  11. /**
  12. * Adjust Brightness and Contrast
  13. *
  14. * @param src [in] InputArray
  15. * @param dst [out] OutputArray
  16. * @param brightness [in] integer, value range [-255, 255]
  17. * @param contrast [in] integer, value range [-255, 255]
  18. *
  19. * @return 0 if success, else return error code
  20. */
  21. int adjustBrightnessContrast(InputArray src, OutputArray dst, int brightness, int contrast)
  22. {
  23. Mat input = src.getMat();
  24. if (input.empty()) {
  25. return -1;
  26. }
  27. dst.create(src.size(), src.type());
  28. Mat output = dst.getMat();
  29. brightness = CLIP_RANGE(brightness, -255, 255);
  30. contrast = CLIP_RANGE(contrast, -255, 255);
  31. /**
  32. Algorithm of Brightness Contrast transformation
  33. The formula is:
  34. y = [x - 127.5 * (1 - B)] * k + 127.5 * (1 + B);
  35. x is the input pixel value
  36. y is the output pixel value
  37. B is brightness, value range is [-1,1]
  38. k is used to adjust contrast
  39. k = tan( (45 + 44 * c) / 180 * PI );
  40. c is contrast, value range is [-1,1]
  41. */
  42. double B = brightness / 255.;
  43. double c = contrast / 255.;
  44. double k = tan((45 + 44 * c) / 180 * M_PI);
  45. Mat lookupTable(1, 256, CV_8U);
  46. uchar* p = lookupTable.data;
  47. for (int i = 0; i < 256; i++)
  48. p[i] = COLOR_RANGE((i - 127.5 * (1 - B)) * k + 127.5 * (1 + B));
  49. LUT(input, lookupTable, output);
  50. return 0;
  51. }
  52. static string window_name = "photo";
  53. static Mat src;
  54. static int brightness = 255;
  55. static int contrast = 255;
  56. static void callbackAdjust(int, void*)
  57. {
  58. Mat dst;
  59. adjustBrightnessContrast(src, dst, brightness - 255, contrast - 255);
  60. imshow(window_name, dst);
  61. }

 【完整演示源码下载地址】

https://download.csdn.net/download/FL1623863129/89633007

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号