Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV: How to get the bounding box for each contour?

Tags:

c++

opencv

** ~ Updated ~ ** Hi , I have a source file and i converted it to below picture , and i have a contour in my program

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

that works fine but i want to add bounding box,find the bounding box for each contour to select all of my objects. What should I do?

like image 646
aH ProgrammeR Avatar asked Jan 06 '23 17:01

aH ProgrammeR


1 Answers

You can get the bounding box for each contour as:

Rect box = boundingRect(contours[i]); 

and you can draw it as:

rectangle(drawing, box, color);

So simply add these two lines in the for loop:

Rect box = boundingRect(contours[i]); 
rectangle(drawing, box, color);
like image 87
Miki Avatar answered Jan 14 '23 22:01

Miki