【opencv】轮廓外接矩形

时间:2022-12-26 12:51:16
<pre name="code" class="cpp">     //找出图片src中所有轮廓的外接矩形
IplImage* src;
src=cvLoadImage((CT2CA)m_strPicPath,1);//读取彩色图
CvMemStorage* storage = cvCreateMemStorage( 0 );//创建一个内存区域,该区域是额可以动态增长的
CvSeq* contours = NULL; //定义一个序列,这些序列可以存放在上面的内存区域里
src=cvLoadImage((CT2CA)m_strPicPath,1);//读取彩色图
cvFindContours( src, storage, &contours, sizeof( CvContour ), CV_RETR_LIST, CV_CHAIN_APPROX_NONE );//检索所有轮廓
/*/-------对于contours的一些基本操作----------
int c=seq->total;//当前轮廓包含多少个元素,这里的元素为点
double length = cvArcLength(seq); //得到指定的那个轮廓的周长,该函数有3个参数:序列,起点(默认计算整条曲线),是否封闭曲线
double area = cvContourArea(seq); //得到指定的那个轮廓的面积
*/
for( ; contours != NULL; contours = contours -> h_next )//循环遍历检索到的所有轮廓
{ //---first method------
CvRect rect = cvBoundingRect( contours, 1 ); //根据序列,返回轮廓外围矩形;
CvRect rect = cvBoundingRect( contours, 1 );
cvRectangle( cpy, cvPoint( rect.x, rect.y ),cvPoint( rect.x + rect.width, rect.y + rect.height ), cvScalar(255,255,0), 3 );

//---second method-------
/* CvBox2D box = cvMinAreaRect2(contours,NULL); //最小外围矩形
//绘制外接最小矩形
CvPoint2D32f p[4];
cvBoxPoints(box,p);
for(int i = 0;i<4;++i)
{
cvLine(src,cvPointFrom32f(p[i]),cvPointFrom32f(p[((i+1)%4)?(i+1):0]),CV_RGB(0,0,255));
} */
}
cvShowImage("src",src);