OpenCV:如何获得每个轮廓的边界框?

时间:2016-02-04 15:07:05

标签: c++ opencv

**〜更新〜** 嗨,我有一个源文件,我把它转换成下面的图片,我的程序中有一个轮廓

void find_contour(int, void*, Mat _mat)
{
    Mat edge_detect_canny;
    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;
    findContours(_mat, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
    Mat drawing = Mat::zeros(_mat.size(), CV_8UC3);
    for (int i = 0; i < contours.size(); i++)
        {
        Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
        drawContours(drawing, contours, i, color, 1, 8, hierarchy, 1, Point());
        }
    IMshow(drawing, "draw-Res", 0);
    imwrite("c:\\draw.bmp", drawing);
    int cs = contours.size();
    cout << cs << "contour.size" << endl;
}

工作正常,但我想添加边界框,找到每个轮廓的边界框以选择我的所有对象。 我该怎么办?

1 个答案:

答案 0 :(得分:5)

您可以获得每个轮廓的边界框:

Rect box = boundingRect(contours[i]); 

你可以把它画成:

rectangle(drawing, box, color);

所以只需在for循环中添加这两行:

Rect box = boundingRect(contours[i]); 
rectangle(drawing, box, color);