1
0

cv05_removeShadow.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include <windows.h>
  2. #include <opencv2/opencv.hpp>
  3. #pragma comment(lib, "opencv_world4100.lib")
  4. using namespace cv;
  5. using namespace std;
  6. int main(int argc, char *argv[])
  7. {
  8. if (argc != 2) {
  9. puts("彩色图片去除阴影App By 蘭雅 捞鱼吧 bbs.lyvba.com\n");
  10. puts("Usage: removeShadow image\n");
  11. int i = getchar();
  12. return 8;
  13. }
  14. Mat src = imread(argv[1]);
  15. if (src.empty()) {
  16. puts("Error: Could not open or find the image.\n");
  17. return 1;
  18. }
  19. // 1. 将图像转换为 HSV 色彩空间
  20. Mat hsv;
  21. cvtColor(src, hsv, COLOR_BGR2HSV);
  22. // 分离通道
  23. vector<Mat> hsvChannels;
  24. split(hsv, hsvChannels);
  25. // 2. 对 V 通道进行处理
  26. Mat vChannel = hsvChannels[2];
  27. Mat element = getStructuringElement(MORPH_RECT, Size(3, 3));
  28. int iteration = 9;
  29. // 3. 膨胀和腐蚀操作
  30. Mat dilateMat;
  31. morphologyEx(vChannel, dilateMat, MORPH_DILATE, element, Point(-1, -1), iteration);
  32. Mat erodeMat;
  33. morphologyEx(dilateMat, erodeMat, MORPH_ERODE, element, Point(-1, -1), iteration);
  34. // 4. 计算去阴影效果
  35. Mat calcMat = ~(erodeMat - vChannel);
  36. normalize(calcMat, calcMat, 0, 255, NORM_MINMAX);
  37. // 5. 将处理后的 V 通道与原始 H 和 S 通道合并
  38. hsvChannels[2] = calcMat;
  39. Mat result;
  40. merge(hsvChannels, hsv);
  41. // 6. 将 HSV 转换回 BGR 色彩空间
  42. cvtColor(hsv, result, COLOR_HSV2BGR);
  43. // 7. 将结果保存为图像
  44. imwrite("removeShadow_color.png", result);
  45. // 去阴影结果保存为图像
  46. imwrite("removeShadow.png", calcMat);
  47. imshow("removeShadow.png", calcMat);
  48. waitKey(50);
  49. MessageBoxA(NULL, "彩色图片去除阴影操作完成,感谢您的试用!\n原创软件->捞鱼吧 bbs.lyvba.com", "彩色图片去除阴影App By 蘭雅", MB_ICONINFORMATION);
  50. return 0;
  51. }