cv04_removeShadow.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #include <opencv2/opencv.hpp>
  2. #pragma comment(lib, "opencv_world4100.lib")
  3. using namespace cv;
  4. using namespace std;
  5. int main(int argc, char *argv[])
  6. {
  7. if (argc != 2) {
  8. puts("Usage: cv04_removeShadow image\n");
  9. return 8;
  10. }
  11. Mat src = imread(argv[1]);
  12. // 1.将图像转为灰度图
  13. Mat gray;
  14. cvtColor(src, gray, COLOR_BGR2GRAY);
  15. // imshow("gray", gray);
  16. // 定义腐蚀和膨胀的结构化元素和迭代次数
  17. Mat element = getStructuringElement(MORPH_RECT, Size(3, 3));
  18. int iteration = 9;
  19. // 2.将灰度图进行膨胀操作
  20. Mat dilateMat;
  21. morphologyEx(gray, dilateMat, MORPH_DILATE, element, Point(-1, -1), iteration);
  22. // imshow("dilate", dilateMat);
  23. // 3.将膨胀后的图再进行腐蚀
  24. Mat erodeMat;
  25. morphologyEx(dilateMat, erodeMat, MORPH_ERODE, element, Point(-1, -1), iteration);
  26. // imshow("erode", erodeMat);
  27. // 4.膨胀再腐蚀后的图减去原灰度图再进行取反操作
  28. Mat calcMat = ~(erodeMat - gray);
  29. // imshow("calc", calcMat);
  30. // 5.使用规一化将原来背景白色的改了和原来灰度图差不多的灰色
  31. Mat removeShadowMat;
  32. normalize(calcMat, removeShadowMat, 0, 200, NORM_MINMAX);
  33. // imshow("dst", removeShadowMat);
  34. // waitKey(0);
  35. imwrite("removeShadow.png", removeShadowMat);
  36. return 0;
  37. }