How to draw a rectangle around the contours?

大兔子大兔子 提交于 2019-12-08 02:47:34

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/15590600/how-to-draw-a-rectangle-around-the-contours

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!