1、将Mat转换为IplImage
//! converts header to IplImage; no data is copied
operator IplImage() const;
举例:Mat img;
IplImage *src;
src=&IplImage(img);
2、将IplImage转换为Mat
//! converts old-style IplImage to the new matrix; the data is not copied by default
Mat(const IplImage* img, bool copyData=false);
Ex.
IplImage* pImg = cvLoadImage("lena.jpg");
cv::Mat img(pImg,0); //0是不複製影像,也就是pImg與img的data共用同個記憶體位置,header各自有
3、IplImage是OpenCV中C语言的图像类型;cv::Mat是OpenCV中C++语言的图像类型;
cv::Mat matimg = cv::imread ("heels.jpg");
IplImage* iplimg;
*iplimg = IplImage(matimg);
IplImage* iplimg = cvLoadImage("heels.jpg");
cv::Mat matimg;
matimg = cv::Mat(iplimg);
4、
OpenCV中的CvArr*的定义的一个空类型的指针,可以转换为其派生类CvMat和IplImage,那么如何将其转化为cv::Mat呢,其实很简单,只需要一行代码即可:
// CvArr *_img cv::Mat img = cv::cvarrToMat(_img);
综合:
1、Mat, IplImage, CvMat, CvArr的关系:
1. opencv文档中明确声明,CvMat已经过时了(CvMat is now obsolete, consider using Mat instead)不建议用;
2. 派生关系:CvArr -> CvMat -> IplImage
3. Mat用的一套东西是imread,imshow等,有别于CvArr及其子类的cvLoadImage(),cvShowImage()...
2. 相互转换
所有代码已经过测试,但是这里我就示意一下,真正写的时候不要忘记初始化转化过去的变量。
2.1 Mat与IplImage相互转换
IplImage* src;
某文章说,转换应该是Mat m(src); 而这不会复制内容,真正能复制内容的是:
Mat -> IplImage:
1 Mat m; 2 IplImage* transIplimage = cvCloneImage(&(IplImage) m);
IplImage -> Mat
1 IplImage* transIplImage; 2 Mat m = cvarrToMat(transIplImage,true);
2.2 CvMat与IplImage相互转换
1 IplImage* transIplImage; 2 CvMat* cvmat; 3 cvGetMat(transIplImage,cvmat); 4 cvGetImage(cvmat,transIplImage);
2.3 Mat到CvMat
1 Mat a; 2 3 CvMat *b = cvCreateMat(..........); 4 5 CvMat temp = a; 6 7 cvCopy(&temp, b)
2.4 CvMat到Mat
1 CvMat *a = cvCreateMat(); 2 3 Mat b = Mat(a, true);
3. (多通道)Mat, IplImage, CvMat的元素获取
单通道的网上很多,这里只写多通道:
3.1 IplImage
1 //i is the index of rows 2 //j is the index of cols 3 //c is the index of channel 4 ((uchar*)pImg->imageData+i*pImg->widthStep)[j*3+c] 5 CV_IMAGE_ELEM(pImg,uchar,i,3*j+c)
3.2 Mat
1 Mat m; 2 int h = m.rows; int w = m.cols; 3 int nc = m.channels(); 4 for (int i = 0;i) 5 { 6 for(int j = 0;j ) 7 { 8 Vec3b& elem = m.at (i,j); 9 for (int c = 0; c ) 10 { 11 uchar uc = elem[c] ;//Mat(i,j) of channel c 12 } 13 } 14 }
3.3 CvMat
1 CV_MAT_ELEM(cvmat,uchar,i,3*j+c)
4. 验证获取元素代码(Mat转IplImage)
此代码只用于验证多通道元素获取没有错误,具体用的时候最好还是用opencv直接给的吧(见第3小节)
1 IplImage* cvcvt_mat2IplImage(Mat m) 2 { 3 int h = m.rows; int w = m.cols; 4 int nc = m.channels(); 5 IplImage* pImg = cvCreateImage(cvSize(w,h),8,nc); 6 7 for (int i = 0;i) 8 { 9 for(int j = 0;j ) 10 { 11 Vec3b& elem = m.at (i,j); 12 for (int c = 0; c ) 13 { 14 //以下两种都可以 15 //((uchar*)pImg->imageData+i*pImg->widthStep)[j*3+c] = elem[c]; 16 CV_IMAGE_ELEM(pImg,uchar,i,3*j+c) = elem[c]; 17 } 18 } 19 } 20 return pImg; 21 }