声明:由于该程序是很久前从网络上抄写到教材上,而忘记了记录下网址。
本着好资源共享原则,暂时记为“原创”,分享给初学者。
#include<opencv2\opencv.hpp>
// chap 8 cvConvertHull2
// 随机点 算凸包
void main()
{
IplImage* img=cvCreateImage(cvSize(400,500),8,3);
cvNamedWindow("img");
cvZero(img);
for( ; ; )
{
int count=rand()%100+1;// count = 1 ~ 100
int hullcount=0;
CvPoint* points=(CvPoint*)malloc(count*sizeof(points[0]));
int *hull=(int*)malloc(count*sizeof(hull[0]));
CvMat point_mat=cvMat(1,count,CV_32SC2,points);
CvMat hull_mat=cvMat(1,count,CV_32SC1,hull);
CvPoint pt0;
// --- 赋值 并绘画 随机点 ---//
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;
points[i]=pt0;
cvCircle(img,pt0,2,CV_RGB(255,0,0),CV_FILLED);
}
//-------- calc convexhull2--------------------//
cvConvexHull2(&point_mat,&hull_mat,CV_CLOCKWISE,0);
hullcount=hull_mat.cols;
pt0=points[hull[hullcount-1]];
printf("pt0=cvPoint(%d,%d)\n",points[hull[hullcount-1]]);
for(int i=0;i<hullcount;i++)
{
CvPoint pt=points[hull[i]];
cvLine(img,pt0,pt,CV_RGB(0,0,255));
pt0=pt;
}
//--------------- display result ---------------//
cvShowImage("img",img);
if(cvWaitKey(1000)>0)
break;
cvZero(img);
}
cvReleaseImage(&img);
cvDestroyAllWindows();
}
运行结果:
随机出现一些点,红色显示其凸包。
详细思路:
参考教材:pp:286-288