声明:由于该程序是很久前从网络上抄写到教材上,而忘记了记录下网址。
本着好资源共享原则,暂时记为“原创”,分享给初学者。
#include<opencv2\opencv.hpp>
// chap 8 cvConvertHull2
// 根据 序列 计算 凸包
void main()
{
IplImage* img=cvCreateImage(cvSize(400,500),8,3);
CvMemStorage* storage=cvCreateMemStorage(0);
for(;;)
{
int count=rand()%100+1;// number of random points
int hullcount=0;
CvPoint pt0;
CvSeq* ptseq=cvCreateSeq(CV_SEQ_KIND_GENERIC|CV_32SC2,
sizeof(CvContour),sizeof(CvPoint),storage);
CvSeq* hull;
for( int i=0;i<count;i++)
{
// 产生序列点,布局,位于图中间。
pt0.x=rand()%(img->width/2)+img->width/4;
pt0.y=rand()%(img->height/2)+img->height/4;
cvSeqPush(ptseq,&pt0);
}
hull=cvConvexHull2(ptseq,0,CV_CLOCKWISE,0);
// return_points=0. return(index); return_points=1,return ( points )
hullcount=hull->total;
for( int i=0;i<count;i++)
{ // display the random points
pt0=*CV_GET_SEQ_ELEM(CvPoint,ptseq,i);
cvCircle(img,pt0,2,CV_RGB(255,0,0),CV_FILLED);
}
pt0=**CV_GET_SEQ_ELEM(CvPoint*,hull,hullcount-1);
for(int i=0;i<hullcount;i++)
{ // 用线连起 所有点,形成凸包
CvPoint pt=**CV_GET_SEQ_ELEM(CvPoint*,hull,i);
cvLine(img,pt0,pt,CV_RGB(0,255,0));
pt0=pt;
}
cvShowImage("img",img);
if(cvWaitKey(200)==27)
break;
cvZero(img);
}
cvReleaseImage(&img);
cvReleaseMemStorage(&storage);
cvDestroyWindow("img");
}
运行结果和(一)相同。
两者的区别在于:
1,由矩阵 - mat - 计算随机点产生的凸包;
2,由序列 - seq - 计算随机点产生的凸包。