多边形检测中Canny和approxPolyDP的参数

时间:2014-04-08 17:51:36

标签: c++ opencv canny-operator

我是OpenCV的新手。我知道存在许多方法来检测多边形的轮廓。但是当我尝试检测我绘制的多边形轮廓时,是否存在为我提供解决方案的方式?

P上。 S.对不起我的英文......

我的代码:

Mat src = imread("C:/Users/Nickolay/Desktop/1.jpg");
resize(src, src, Size(400, 400), 0, 0, INTER_CUBIC);
if (src.empty()) 
{
    cout << "Cannot load image!" << endl;
    return -1;
}

//================================

Mat gray;
cvtColor(src, gray, CV_BGR2GRAY);
Mat bw;
Canny(gray, bw, 800, 850, 5, true);
imshow("canny", 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]);
        }
    }
}

//================================

imshow("source", src);
imshow("detected lines", dst);

waitKey(0);

return 0;`

Example

我的问题是如何检测我使用opencv绘制的多边形轮廓?在附加图片中我使用了opencv中的函数,但是我只得到了5个预期的矩形。

2 个答案:

答案 0 :(得分:8)

问题可能是您正在为查找轮廓直接传递边缘图像,这可能包含许多未连接的边。

所以在找到轮廓之前应用Morphology Transformations

   Size kernalSize (5,5);
   Mat element = getStructuringElement (MORPH_RECT, kernalSize, Point(1,1)  );
   morphologyEx( bw, bw, MORPH_CLOSE, element );

查看结果。

轮廓的边界矩形

bounding rectangle for  contours

对于轮廓

approxPolyDP

approxPolyDP for  contours

答案 1 :(得分:1)

您可能还想尝试使用阈值来查找边缘,而不是Canny。

threshold (gray, bw, 0, 255, THRESH_BINARY|THRESH_OTSU);