求轮廓的包围盒

矩形,圆形,椭圆形以及倾斜的矩形(包围面积最小)集中包围盒。用到的四个函数是:

Rect boundingRect(InputArray points)
void minEnclosingCircle(InputArray points, Point2f& center, float& radius)
RotatedRect minAreaRect(InputArray points)
RotatedRect fitEllipse(InputArray points)

输入的参数都是轮廓,下面是程序代码:

nt main( int argc, char** argv )
    {
    //装入图像
    src = imread("../ballon.jpg", 1 );

    //转化为灰度图并进行blur操作
    cvtColor( src, src_gray, CV_BGR2GRAY );
    blur( src_gray, src_gray, Size(3,3) );

    namedWindow( "source", CV_WINDOW_AUTOSIZE );
    imshow( "source", src );

    Mat threshold_output;
    vector > contours;
    vector hierarchy;

    //得到二值图像
    threshold( src_gray, threshold_output, thresh, 255, THRESH_BINARY );
    //查找轮廓
    findContours( threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );

    //对轮廓进行多边形近似处理求得圆形和四边形包围盒
    vector > contours_poly( contours.size() );
    vector boundRect( contours.size() );
    vectorcenter( contours.size() );
    vectorradius( contours.size() );

    //得到每个轮廓的包围盒RECT以及园,园用中心和半径表示
    for( int i = 0; i < contours.size(); i++ )
        { 
        approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true );
        boundRect[i] = boundingRect( Mat(contours_poly[i]) );
        minEnclosingCircle( (Mat)contours_poly[i], center[i], radius[i] );
        }


    //画轮廓以及它的四边形和原型包围盒
    Mat drawing = Mat::zeros( threshold_output.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_poly, i, color, 1, 8, vector(), 0, Point() );
        //tl是左上角坐标, br是右下角坐标
        rectangle( drawing, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0 );
        circle( drawing, center[i], (int)radius[i], color, 2, 8, 0 );
        }

    namedWindow( "Contours", CV_WINDOW_AUTOSIZE );
    imshow( "Contours", drawing );


    while(1)
        waitKey(0);
    return(0);
    }

原文出处:https://www.cnblogs.com/mikewolf2002/p/3427079.html

你可能感兴趣的:(【OpenCV学习笔记】)