Mat 是OpenCV和C++的接口矩阵类,ImlImage是OpenCV和C语言的接口的结构体,但是C++程序有时候时候还是要用到ImlImage。注意:opencv3.0以后的版本和之前的版本有些差异。在opencv3.0之前,Mat类中提供了Mat(const IplImage* img, bool copyData=false);构造函数来实现IplImage到Mat类的转换,copyData=false时实现浅拷贝,只拷贝数据头,copyData=true实现深拷贝,连同里面的数据一起拷贝。但是在opencv3.0之后,此方法被抛弃。#include "opencv2/imgcodecs.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include
#include
#include
#include
#include
using namespace cv;
using namespace std;
int main()
{
/*************************IplImage2Mat方式1********************************/
#if 0
/*IplImage2Mat*/
string str="Ipl2Mat";
IplImage *m_image = cvLoadImage("lb.jpg");
Mat m_mat;
m_mat = cvarrToMat(m_image);
imshow(str, m_mat);
waitKey(0);
Mat myMat = imread("lb1.jpg");
/*先浅拷贝后深拷贝*/
IplImage* _m_image = &IplImage(myMat);
IplImage* image = cvCloneImage(_m_image);
cvNamedWindow("Mat2Ipl");
cvShowImage("Mat2Ipl", image);
waitKey(0);
#endif
/*************************IplImage2Mat方式2********************************/
#if 0
IplImage* Iplimg = cvLoadImage("lb1.jpg");
IplImage* srcImg;
Mat M(srcImg, true);
//Mat mat = Mat(Iplimg);
//使用Mat的构造函数:Mat::Mat(const IplImage* img, bool copyData=false); 默认情况下copyData为false
IplImage* srcImg = cvLoadImage("Lena.jpg");
//注意:以下三种效果一致,均为浅拷贝
Mat M(srcImg);
Mat M(srcImg, false);
Mat M = srcImg;
//注意:当将参数copyData设为true后,则为深拷贝(复制整个图像数据)
Mat M(srcImg, true);
/****************浅拷贝*******************/
#endif
#if 0
Mat M=imread("lb1.jpg");
IplImage img = M;
IplImage imgx = IplImage(img);
cvShowImage("方法三", dst);
waitKey(0);
#endif
/*方法三之浅拷贝加深拷贝*/
Mat M = imread("lb1.jpg");
//IplImage *_src = cvLoadImage("lb1.jpg");
IplImage img = M;
IplImage imgx = IplImage(M);
IplImage *src = &imgx;
IplImage *dst = cvCreateImage(cvGetSize(src), IPL_DEPTH_8U, 1);
cvCvtColor(src, dst, CV_RGB2GRAY);
cvShowImage("方法三", dst);
waitKey(0);
cvDestroyAllWindows();
return 0;
}
单纯浅拷贝时,不可以对图像数据做处理,否则程序出现崩溃。