1)cvApproxPoly:使用多边形去逼近轮廓,使顶点数目变少。
CVAPI(CvSeq*) cvApproxPoly( const void* src_seq, int header_size, CvMemStorage* storage,
int method, double parameter, int parameter2 CV_DEFAULT(0));
CvSeq* 返回值对应第一个 轮廓(可用h_next和v_next访问其他轮廓)
src_seq 要处理的目标序列
header_size 为返回结果指定头结构大小
storage 为返回结果指定新的内存存储器
method 算法:目前只有CV_POLY_APPOX_DP
parameter 逼近算法参数,指定逼近精度,曲线1、n
parameter2 逼近算法参数。若为0,只处理src_seq指向的轮廓。1则处理整个双向链表中的所有轮廓。
(h_next和v_next可达的)
2)CvTreeNodeIterator:序列树
typedef struct CvTreeNodeIterator
{
const void* node; //结点
int level; //树的当前深度
int max_level;//最大深度
}
CvTreeNodeIterator;
代码:
#include<cv.h>
#include<highgui.h>
int main()
{
IplImage* src = NULL;
IplImage* img = NULL;
IplImage* dst = NULL;
CvMemStorage* storage = cvCreateMemStorage (0);
CvMemStorage* storage1 = cvCreateMemStorage (0);
CvSeq* contour = 0;
CvSeq* cont;
CvSeq* mcont;
src = cvLoadImage ("a4.jpg", 1);
img = cvCreateImage (cvGetSize(src), IPL_DEPTH_8U, 1);
dst = cvCreateImage (cvGetSize(src), src->depth, src->nChannels);
cvCvtColor (src, img, CV_BGR2GRAY);
cvThreshold (img, img, 100, 200, CV_THRESH_BINARY);
cvFindContours (img, storage, &contour, sizeof(CvContour), CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
if (contour)
{
CvTreeNodeIterator iterator;
cvInitTreeNodeIterator (&iterator, contour, 1);
while (0 != (cont = (CvSeq*)cvNextTreeNode (&iterator)))
{
mcont = cvApproxPoly (cont, sizeof(CvContour), storage1, CV_POLY_APPROX_DP, cvContourPerimeter(cont)*0.02,0);
cvDrawContours (dst, mcont, CV_RGB(255,0,0),CV_RGB(0,0,100),1,2,8,cvPoint(0,0));
}
}
cvNamedWindow ("Contour", 1);
cvShowImage ("Contour", dst);
cvSaveImage("result.jpg",dst);
cvWaitKey (0);
cvReleaseMemStorage (&storage);
cvReleaseImage (&src);
cvReleaseImage (&img);
cvReleaseImage (&dst);
return 0;
}
结果:
输入原图:
输出结果: