今天我们来看另外一个opencv例程,就是 (TUTORIAL) interoperability_with_OpenCV_1。
众所周知,opencv1.0的函数API以c语言编写的,提供的都是c语言的函数接口,用来存储图片的结构类型则为IplImage,而从opencv2.0开始,数据存储的变为了Mat 类。那么如何实现Mat格式与opencv1.0中IplImage的兼容性和互用呢,从interoperability_with_OpenCV_1 这个例程中,我们可以找到部分解答。废话少说,直接上源码。
#include <stdio.h>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv; // The new C++ interface API is inside this namespace. Import it.
using namespace std;
// 程序使用说明
static void help( char* progName)
{
cout << endl << progName
<< " shows how to use cv::Mat and IplImages together (converting back and forth)." << endl
<< "Also contains example for image read, spliting the planes, merging back and " << endl
<< " color conversion, plus iterating through pixels. " << endl
<< "Usage:" << endl
<< progName << " [image-name Default: lena.jpg]" << endl << endl;
}
// comment out the define to use only the latest C++ API // 控制参数,只使用C++API还是使用C、C++的混合API
#define DEMO_MIXED_API_USE
int main( int argc, char** argv )
{
help(argv[0]);
const char* imagename = argc > 1 ? argv[1] : "lena.jpg"; //如果输入参数不够,则使用默认图片"lena.jpg",注意应该在当前路径
#ifdef DEMO_MIXED_API_USE //使用混合API时候
Ptr<IplImage> IplI = cvLoadImage(imagename); // Ptr<T> is safe ref-counting pointer class // 智能指针
if(IplI.empty()) //判断是否成功载入图片
{
cerr << "Can not load image " << imagename << endl;
return -1;
}
Mat I(IplI); // Convert to the new style container. Only header created. Image not copied. // 将IplImage 格式转成Mat类型,注意只复制数据指针,没有拷贝数据
#else
Mat I = imread(imagename); // the newer cvLoadImage alternative, MATLAB-style function
if( I.empty() ) // same as if( !I.data )
{
cerr << "Can not load image " << imagename << endl;
return -1;
}
#endif
// convert image to YUV color space. The output image will be created automatically.
Mat I_YUV;
cvtColor(I, I_YUV, COLOR_BGR2YCrCb); //cvtColor API,定义在 imgpro库中ÿ