1
0

cv07_cleanLight.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include <opencv2/opencv.hpp>
  2. #include <iostream>
  3. #pragma comment(lib, "opencv_world4100.lib")
  4. using namespace cv;
  5. using namespace std;
  6. void removeShadow(const Mat& src, Mat& dst) {
  7. // 1. 将图像转换为 HSV 色彩空间
  8. Mat hsv;
  9. cvtColor(src, hsv, COLOR_BGR2HSV);
  10. // 分离通道
  11. vector<Mat> hsvChannels;
  12. split(hsv, hsvChannels);
  13. // 2. 对 V 通道进行处理
  14. Mat vChannel = hsvChannels[2];
  15. Mat element = getStructuringElement(MORPH_RECT, Size(3, 3));
  16. int iteration = 9;
  17. // 3. 膨胀和腐蚀操作
  18. Mat dilateMat;
  19. morphologyEx(vChannel, dilateMat, MORPH_DILATE, element, Point(-1, -1), iteration);
  20. Mat erodeMat;
  21. morphologyEx(dilateMat, erodeMat, MORPH_ERODE, element, Point(-1, -1), iteration);
  22. // 4. 计算去阴影效果
  23. Mat calcMat = ~(erodeMat - vChannel);
  24. normalize(calcMat, calcMat, 0, 255, NORM_MINMAX);
  25. // 5. 将处理后的 V 通道与原始 H 和 S 通道合并
  26. hsvChannels[2] = calcMat;
  27. merge(hsvChannels, hsv);
  28. // 6. 将 HSV 转换回 BGR 色彩空间
  29. cvtColor(hsv, dst, COLOR_HSV2BGR);
  30. }
  31. int main(int argc, char** argv) {
  32. // 读取输入图像
  33. Mat src = imread("test.webp");
  34. if (src.empty()) {
  35. cerr << "无法加载图像\n";
  36. return -1;
  37. }
  38. Mat result;
  39. removeShadow(src, result);
  40. // 调整对比度和亮度
  41. double alpha = 1.1; // 对比度因子
  42. int beta = 5; // 亮度偏移
  43. convertScaleAbs(result, result, alpha, beta);
  44. // 获取原始图像比例
  45. Size srcSize = src.size();
  46. // 计算显示尺寸,保持比例
  47. int displayHeight = 1080;
  48. int displayWidth = srcSize.width * displayHeight / srcSize.height;
  49. // 调整图像大小以保持比例
  50. Mat resizedSrc, resizedResult;
  51. resize(src, resizedSrc, Size(displayWidth, displayHeight));
  52. resize(result, resizedResult, Size(displayWidth, displayHeight));
  53. // 拼接图像
  54. Mat combined;
  55. hconcat(resizedSrc, resizedResult, combined);
  56. // 显示结果
  57. imshow("原图和去除阴影后的图像对比", combined);
  58. waitKey(0);
  59. // 保存结果
  60. imwrite("output.jpg", result);
  61. return 0;
  62. }