joshualan
joshualan

Reputation: 2140

How to draw a rectangle around the contours?

I am just starting out with opencv and I am trying to make a program that puts squares around a picture of rocks on some sand. The documentation for the function here includes an example of how to use it.

findContours( src, contours, hierarchy,
  CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );

The prototype of findContours is

void findContours(InputOutputArray image, OutputArrayOfArrays contours, OutputArray hierarchy, int mode, int method, Point offset=Point()) ;

I have two questions.
1. The third argument in the example hierarchy is a vector<Vec4i> does not match the type findContours expects. Why is that?
2. How does one use the data stored in contours to find where the contours are to create a bounding box?

Upvotes: 2

Views: 10832

Answers (1)

berak
berak

Reputation: 39796

std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours( mask, contours, hierarchy, cv::RETR_CCOMP, cv::CHAIN_APPROX_TC89_KCOS);
for ( size_t i=0; i<contours.size(); ++i )
{
    cv::drawContours( img, contours, i, Scalar(200,0,0), 1, 8, hierarchy, 0, Point() ); 
    cv::Rect brect = cv::boundingRect(contours[i]);
    cv::rectangle(img, brect, Scalar(255,0,0));
}

Upvotes: 4

Related Questions