0

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

这是我的代码:

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;
 }

这是我的输出:

在此处输入图像描述

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

4

1 回答 1

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);

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

于 2014-04-12T12:48:18.883 回答