右边是源图
仔细看可以发现黄色方框canny出结果有内外两层边缘
如何忽略内边缘?或者如何让canny把黄色方框直接识别成一个方框?
源码如下
- auto testtest = cv::imread("test4.jpg");
- if (!testtest.size)
- {
- OutputDebugStringA("Failed to load testtest.png");
- return;
- }
- cv::Mat gray(testtest.cols, testtest.rows, CV_8UC1);
- cv::cvtColor(testtest, gray, cv::COLOR_RGB2GRAY);
- cv::Mat canny, contour;
-
- cv::Canny(gray, canny, 10, 200, 3, true);
- contour = cv::Mat::zeros(canny.rows, canny.cols, CV_8UC3);
- std::vector<std::vector<cv::Point>> vContours, vCurve;
- std::vector<cv::Vec4i> vHierarchy;
- cv::findContours(canny, vContours, vHierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE, cv::Point(0, 0));
- cv::RNG g_rng(12345);
- cv::Scalar color = cv::Scalar(g_rng.uniform(0, 255), g_rng.uniform(0, 255), g_rng.uniform(0, 255));
- std::vector<cv::Point> approx;
- std::vector<std::vector<cv::Point>> squares;
- for (size_t i = 0; i < vContours.size(); i++)
- {
- cv::approxPolyDP(cv::Mat(vContours[i]), approx, 1.0, true);
- if (approx.size() == 4 &&
- fabs(cv::contourArea(cv::Mat(approx))) > 100 &&
- cv::isContourConvex(cv::Mat(approx)))
- {
- double maxCosine = 0;
- for (int j = 2; j < 5; j++)
- {
- double cosine = fabs(Angle(approx[j - 1], approx[j - 2], approx[j % 4]));
- maxCosine = MAX(maxCosine, cosine);
- }
- if (maxCosine < 0.3)
- {
- squares.push_back(approx);
- }
- }
- }
- drawContours(contour, squares, -1, color, 1, 8);
- imshow("test image", testtest);
- imshow("canny image", canny);
- imshow("contour Image", contour);
- cv::waitKey();
复制代码
|