基础知识
自从版本2.0,OpenCV采用了新的数据结构,用Mat类结构取代了之前用extended C写的cvMat和lplImage,更加好用啦,最大的好处就是更加方便的进行内存管理,对写更大的程序是很好的消息。
#include<opencv2\opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc,char *argv[])
{
Mat image; //声明类
image = imread("lena.jpg", IMREAD_COLOR);
if (!image.data){ // Check for invalid input
cout << "Could not open or find the image" << std::endl;
return -1;
}
Mat gray_image;
cvtColor(image, gray_image, CV_BGR2GRAY); //将彩色图像变为灰度图像
imwrite("Gray_Image.jpg", gray_image); //write picture
namedWindow("Color image", CV_WINDOW_AUTOSIZE);
namedWindow("Gray image", CV_WINDOW_AUTOSIZE);
imshow("Color image", image); //原图
imshow("Gray image", gray_image); //灰色
waitKey(0);
return 0;
}
Mat解析
1. Mat是一个类,有构造函数,赋值函数等
1 Mat A, C; // creates just the header parts
2 A = imread(argv[1], CV_LOAD_IMAGE_COLOR); // here we’ll know the method used (allocate matrix)
3 Mat B(A); // Use the copy constructor
4 C = A; // Assignment operator
2. 如果要拷贝自己的矩阵:
1 Mat F = A.clone();
2 Mat G;
3 A.copyTo(G);
3. 构造函数解析
Mat M(2,2, CV_8UC3, Scalar(0,0,255));
cout << "M = " << endl << " " << M << endl << endl;
构造2*2的矩阵。
CV_[The number of bits per item][Signed or Unsigned][Type Prefix]C[The channel number]
CV_8UC3 means we use unsigned char types that are 8 bit long and each pixel has three of these to form the three channels.
4. 与原始的转换
IplImage* img = cvLoadImage("greatwave.png", 1);
Mat mtx(img); // convert IplImage* -> Mat
Mat I;
IplImage* pI = &I.operator IplImage();
CvMat* mI = &I.operator CvMat();
5. 改变矩阵creat()函数
不能用来初始化一个矩阵,它不是构造函数,它用来改变一个已有的矩阵的格式。
Create() function:
M.create(4,4, CV_8UC(2));
cout << "M = "<< endl << " " << M << endl << endl;
6. Matlab类型初始化操作
Mat E = Mat::eye(4, 4, CV_64F);
cout << "E = " << endl << " " << E << endl << endl;
Mat O = Mat::ones(2, 2, CV_32F);
cout << "O = " << endl << " " << O << endl << endl;
Mat Z = Mat::zeros(3,3, CV_8UC1);
cout << "Z = " << endl << " " << Z << endl << endl;