链接丢失(由Canny)边缘

时间:2014-04-12 10:19:25

标签: c++ opencv edge-detection canny-operator

我需要检测图像中的所有矩形。

这是我的代码:

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

    Mat bw;
    Canny(src, bw, 50, 200, 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.01, true);

        if (approx.size() >= 4 && (approx.size() <= 6))
        {
            int vtc = approx.size();
            vector<double> cos;
            for(int j = 2; j < vtc + 1; j++)
                cos.push_back(Angle(approx[j%vtc], approx[j-2], approx[j-1]));

            sort(cos.begin(), cos.end());

            double mincos = cos.front();
            double maxcos = cos.back();

            if (vtc == 4)// && mincos >= -0.5 && maxcos <= 0.5)
            {
                Rect r = boundingRect(countours[i]);
                double ratio = abs(1 - (double)r.width / r.height);

                line(dst, approx.at(0), approx.at(1), cvScalar(0,0,255),4);
                line(dst, approx.at(1), approx.at(2), cvScalar(0,0,255),4);
                line(dst, approx.at(2), approx.at(3), cvScalar(0,0,255),4);
                line(dst, approx.at(3), approx.at(0), cvScalar(0,0,255),4);
                SetLabel(dst, "RECT", countours[i]);
            }
        }
    }

    return dst;
 }

这是我的输出:

enter image description here

而是17个矩形(16个小和1个大)我只有12个矩形。 我是opencv的新手,也许我将错误的参数传递给Canny函数和morphologyEx ... 所以,我的问题: 我做错了什么? 我该如何修理?

1 个答案:

答案 0 :(得分:0)

你可以做的是使用通常的侵蚀扩张技巧。在Matlab中,我通常会执行以下操作来创建蒙版。这会使线条更大并且流动在一起。

%Create Structuring element
sel = strel('disk', 1);
% bw is the black and white (binary image) created using e.g. Otsu thresholding
bw2 = imcomplement(bw);
bw3 = imerode(bw2, sel);
bw4 = imdilate(bw3, sel);
tightmask = imcomplement(bw4);

我经常使用它来查找图像中的独立组件

相关问题