用CvSeq的函數創建圓和矩形,這兩個圖像用點序列來表示。
有關序列的讀寫方法可以自行學習,這裏只給出一個示例
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
using namespace std;
using namespace cv;
#define CVX_RED CV_RGB(0xff, 0x00, 0x00)
#define CVX_GREEN CV_RGB(0x00, 0xff, 0x00)
#define CVX_BLUE CV_RGB(0x00, 0x00, 0xff)
void DrawBox(IplImage* img)
{
/*1、初始化相關變量*/
CvBox2D box ;
CvPoint2D32f center;
CvSize2D32f size;
center.x = 50;
center.y = 50;
size.width = 30;
size.height = 30;
box.center = center;
box.size = size;
CvPoint2D32f point[4];
int i;
for ( i=0; i<4; i++)
{
point[i].x = 0;
point[i].y = 0;
}
/*2、計算CvBox2D結構表示矩形的4頂點*/
cvBoxPoints(box, point); //計算二維盒子頂點,把box的點賦值給point
/*3、把float類型的點轉化成int類型*/
CvPoint pt[4];
for ( i=0; i<4; i++)
{
pt[i].x = (int)point[i].x;
pt[i].y = (int)point[i].y;
}
/*4、開闢一個內存管理器並創建一個序列*/
CvMemStorage* store = cvCreateMemStorage(0);
CvSeq* seq = cvCreateSeq(CV_SEQ_ELTYPE_POINT | CV_SEQ_KIND_CURVE | CV_SEQ_FLAG_CLOSED,sizeof(CvContour),sizeof(CvPoint),store);
/*5、數據的存儲和提取*/
for (int j = 0; j < 4; j++)
{
cvSeqPush(seq,&pt[j]);
}
for (int j = 0; j < seq->total; j++)
{
CvPoint* p=(CvPoint*)cvGetSeqElem(seq,j);
printf("p->x=%d,p->y=%d\n",p->x,p->y);
}
/*6、繪製圖形*/
cvDrawContours(img,seq,CV_RGB(255,255,255),CV_RGB(255,255,255),1,3,8);
cvShowImage("Box", img);
cvReleaseMemStorage(&store);
}
void DrawCircle(IplImage* img)
{
/*1、開闢一個內存管理器並創建一個序列*/
CvMemStorage* store = cvCreateMemStorage(0);
CvSeq* seq = cvCreateSeq(CV_SEQ_ELTYPE_POINT | CV_SEQ_KIND_CURVE |CV_SEQ_FLAG_CLOSED,sizeof(CvContour),sizeof(CvPoint),store);
/*2、繪製圓*/
CvPoint pt;
for(int x=25; x<25+50; x++)
{
float y = 50 + sqrt(25*25.0-(x-50)*(x-50));
pt.x = x;
pt.y = y;
cvSeqPush(seq,&pt);
}
for(int x=25+50; x>25; x--)
{
float y = 50 - sqrt(25*25.0-(x-50)*(x-50));
pt.x = x;
pt.y = y;
cvSeqPush(seq,&pt);
}
for (int j = 0; j < seq->total; j++)
{
CvPoint* p=(CvPoint*)cvGetSeqElem(seq,j);
printf("p->x=%d,p->y=%d\n",p->x,p->y);
}
cvDrawContours(img,seq,CV_RGB(255,255,255),CV_RGB(255,255,255),1,3,8);
cvShowImage("Circle", img);
cvReleaseMemStorage(&store);
}
int main()
{
/*1、申請內存、創建一個圖片、*/
CvMemStorage* storage = cvCreateMemStorage();
IplImage* img = cvCreateImage(cvSize(200,200),8,3);
cvZero(img);
cvShowImage("img", img);
/*2、繪製矩形*/
DrawBox(img);
cvSetZero(img);
/*3、繪製圓*/
DrawCircle(img);
cvWaitKey(100000);
cvReleaseImage(&img);
cvReleaseMemStorage(&storage);
return 1;
}