一、Mat类创建
Mat img;//创建无初始化矩阵 Mat img1(200,100,CV_8UC1);//200行,100列(长200,宽100) Mat img2(Size(200,100),CV_8UC3,Scalar(0,255,0));//长100,宽200 Mat img3(200,100,CV_8UC3,Scalar(0,255,0));//创建200行,100列的8位三通道矩阵 Mat img4(200,100,CV_8UC1,Scalar(255));//创建单通道矩阵
1 #include2 using namespace cv; 3 4 void main(){ 5 Mat img1=imread("E://1.jpg"); 6 Mat img2(img1); 7 Mat img3=img1; 8 Mat img4=img1.clone(); 9 Mat img5;10 img1.copyTo(img5);11 12 cvtColor(img1,img1,CV_BGR2HSV);//BGR图转为HSV图13 imshow("img1",img1);14 imshow("img2",img2);15 imshow("img3",img3);//image1/2/3跟随原图变化16 imshow("img4",img4);17 imshow("img5",img5);//image4/5不会跟随原图变化18 waitKey(0);19 }
二、基本绘图函数
1、画线、画圆、画矩形
1 #include2 using namespace cv; 3 4 void main(){ 5 Mat img(500,400,CV_8UC3,Scalar(255,255,255));//创建一个500行400列,3通道(即彩色图)的白色图 6 line(img,Point(10,10),Point(100,250),Scalar(0,255,255),20,8);//在img图中画一条黄线,线宽为20,线型为8联通(一般都设置为8) 7 circle(img,Point(200,100),50,Scalar(0,255,255),15,8); //以(200,100)为圆心,半径为50,线宽为15画空心圆 8 circle(img,Point(200,250),50,Scalar(0,255,255),-1,8); //设置为-1时,画实心圆 9 rectangle(img,Point(10,100),Point(200,200),Scalar(0,0,255),1,8); //传入坐上、右下角坐标,画空心矩形10 rectangle(img,Rect(200,300,100,50),Scalar(0,255,0),-1,8); //传矩形数据(左上角坐标(200,300)和宽100,高50),画实心绿色矩形11 12 imshow("drawing",img);13 waitKey(0);14 }
2、画椭圆、画多边形、写入文字
1 #include2 using namespace cv; 3 4 void main(){ 5 Mat img(600,650,CV_8UC3,Scalar(255,255,255)); 6 ellipse(img,Point(200,200),Size(180,80),15,0,360,Scalar(0,255,255),10,8); //画椭圆,(200,200)为中点,15旋转角度,0~360度,长轴180,短轴80 7 ellipse(img,RotatedRect(Point(350,350),Size(150,100),40),Scalar(0,255,0),-1,8); //画椭圆,40旋转角度 8 9 Point ppt[]={Point(120,50),Point(180,50),Point(210,100),Point(180,150),Point(120,150),Point(90,100)};10 Point ppt2[]={Point(80,400),Point(80,550),Point(250,500),Point(300,550)};//定义点集11 const Point* pts[]={ppt};12 const Point* pts2[]={ppt2};13 int npt[]={ 6};14 int npt2[]={ 4};15 fillPoly(img,pts,npt,1,Scalar(255,255,0),8); //画填充多边形16 polylines(img,pts2,npt2,1,false,Scalar(0,100,200),2,8); //画多边形,false为不闭合,true为闭合17 18 putText(img,"China",Point(400,400),CV_FONT_BLACK,2,Scalar(100,100,100),5,8);//写入文字19 20 imshow("drawing",img);21 waitKey(0);22 }