一、Mat类
1、Mat类的创建
1 Mat img;//创建无初始化矩阵 2 Mat img1(200,100,CV_8UC1);//200行,100列(长200,宽100) 3 Mat img2(Size(200,100),CV_8UC3,Scalar(0,255,0));//长100,宽200 4 Mat img3(200,100,CV_8UC3,Scalar(0,255,0));//创建200行,100列的8位三通道矩阵 5 Mat img4(200,100,CV_8UC1,Scalar(255));//创建单通道矩阵
2、Mat类赋值拷贝
1 Mat img(100, 200, CV_8UC3, Scalar(0, 255, 0)); 2 Mat img2(img);//和原图像指向同一数据块,跟随原图改变 3 Mat img3 = img;//和原图像指向同一数据块,跟随原图改变 4 Mat img4 = img.clone();//创建一个原图像的副本,不会随原图像改变 5 Mat img5; 6 img5.copyTo(img5);//创建一个原图像的副本,不会随原图像改变
【示例】
1 //图像的拷贝 2 #include <opencv2/opencv.hpp> 3 4 using namespace cv; 5 6 int main(){ 7 Mat img1=imread("1.jpg"); 8 Mat img2(img1); 9 Mat img3=img1; 10 Mat img4=img1.clone(); 11 Mat img5; 12 img1.copyTo(img5); 13 14 cvtColor(img1,img1,CV_BGR2HSV);//BGR图转为HSV图 15 imshow("img1",img1); 16 imshow("img2",img2); 17 imshow("img3",img3);//image1/2/3跟随原图变化 18 imshow("img4",img4); 19 imshow("img5",img5);//image4/5不会跟随原图变化 20 waitKey(0); 21 22 return 0; 23 }
二、基本的绘图函数
1、画线、画圆、画矩形
1 //基本的绘图函数 2 #include <opencv2/opencv.hpp> 3 4 using namespace cv; 5 6 int main(){ 7 //创建一个500行400列,3通道(即彩色图)的白色图 8 Mat img(500,400,CV_8UC3,Scalar(255,255,255)); 9 10 //在img图中画一条黄线,线宽为20,线型为8联通(一般都设置为8) 11 line(img,Point(10,10),Point(100,250),Scalar(0,255,255),20,8); 12 13 //以(200,100)为圆心,半径为50,线宽为15画空心圆 14 circle(img,Point(200,100),50,Scalar(0,255,255),15,8); 15 16 //设置为-1时,画实心圆 17 circle(img,Point(200,250),50,Scalar(0,255,255),-1,8); 18 19 //传入坐上、右下角坐标,画空心矩形 20 rectangle(img,Point(10,100),Point(200,200),Scalar(0,0,255),1,8); 21 22 //传矩形数据(左上角坐标(200,300)和宽100,高50),画实心绿色矩形 23 rectangle(img,Rect(200,300,100,50),Scalar(0,255,0),-1,8); 24 25 imshow("drawing",img); 26 waitKey(0); 27 28 return 0; 29 }
2、画椭圆、画多边形、写入文字
1 //画椭圆、画多边形、写入文字 2 #include <opencv2/opencv.hpp> 3 using namespace cv; 4 5 int main(){ 6 //创建一个600*500大小,3通道的白色图片 7 Mat img(600,650,CV_8UC3,Scalar(255,255,255)); 8 9 //画椭圆,(200,200)为中点,15旋转角度,0~360度,长轴180,短轴80 10 ellipse(img,Point(200,200),Size(180,80),15,0,360,Scalar(0,255,255),10,8); 11 //画椭圆,40旋转角度 12 ellipse(img,RotatedRect(Point(350,350),Size(150,100),40),Scalar(0,255,0),-1,8); 13 14 //定义点集 15 Point ppt[]={Point(120,50),Point(180,50),Point(210,100),Point(180,150),Point(120,150),Point(90,100)}; 16 Point ppt2[]={Point(80,400),Point(80,550),Point(250,500),Point(300,550)}; 17 const Point* pts[]={ppt}; 18 const Point* pts2[]={ppt2}; 19 int npt[]={6}; 20 int npt2[]={4}; 21 22 //画填充多边形 23 fillPoly(img,pts,npt,1,Scalar(255,255,0),8); 24 25 //画多边形,false为不闭合,true为闭合 26 polylines(img,pts2,npt2,1,false,Scalar(0,100,200),2,8); 27 28 //写入文字 29 putText(img,"China",Point(400,400),CV_FONT_BLACK,2,Scalar(100,100,100),5,8); 30 31 imshow("drawing",img); 32 waitKey(0); 33 34 return 0; 35 }
原文地址:https://www.cnblogs.com/Long-w/p/9661486.html
时间: 2024-10-13 19:59:37