1

当线在多边形中时,如何检测线和多边形?我正在使用 Canny 检测 + approxPolyDP,但我得到的是两个七边形,而不是线 + 多边形。例如,这里: 在此处输入图像描述

我的代码:

Mat PolygonsDetection(Mat src)
 {
    Mat gray;
    cvtColor(src, gray, CV_BGR2GRAY);

    Mat bw;
    Canny(src, bw, 40, 120, 3, true);
    imshow("canny", bw);

    morphologyEx(bw, bw, MORPH_CLOSE, cv::noArray(),cv::Point(-1,-1),1);

    imshow("morph", bw);

    vector<vector<Point>> countours;
    findContours(bw.clone(), countours, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);

    vector<Point> approx;
    Mat dst = src.clone();

    for(int i = 0; i < countours.size(); i++)
    {
        approxPolyDP(Mat(countours[i]), approx, arcLength(Mat(countours[i]), true) * 0.020, true);
        int vtc = approx.size();

        if ((vtc == 2) || (vtc == 4) || (vtc == 7))
        {
            if (vtc == 7)
            {
                cv::line(dst, approx.at(0), approx.at(1), cvScalar(0,255,0),4);
                cv::line(dst, approx.at(1), approx.at(2), cvScalar(0,255,0),4);
                cv::line(dst, approx.at(2), approx.at(3), cvScalar(0,255,0),4);
                cv::line(dst, approx.at(3), approx.at(4), cvScalar(0,255,0),4);
                cv::line(dst, approx.at(4), approx.at(5), cvScalar(0,255,0),4);
                cv::line(dst, approx.at(5), approx.at(6), cvScalar(0,255,0),4);
                cv::line(dst, approx.at(6), approx.at(0), cvScalar(0,255,0),4);

                SetLabel(dst, std::to_string((long long)cellCounter), countours[i]);
            }
            else if (vtc == 4)
            {

                line(dst, approx.at(0), approx.at(1), cvScalar(255,0,0),4);
                line(dst, approx.at(1), approx.at(2), cvScalar(255,0,0),4);
                line(dst, approx.at(2), approx.at(3), cvScalar(255,0,0),4);
                line(dst, approx.at(3), approx.at(0), cvScalar(255,0,0),4);

                SetLabel(dst, std::to_string((long long)cellCounter), countours[i]);
            }
            eslse if (vtc == 2)
            {
                // Never not comes here
            }
        }
    }
    return dst;
 }
4

0 回答 0