OpenCV Tutorials —— Interoperability with OpenCV 1

新版本的OpenCV 使用Mat作为基本的图像容器,而代替旧版本的 CvMat 和 IplImage

All the OpenCV related stuff is put into the cv namespace to avoid name conflicts with other libraries data structures and functions. Therefore, either you need to prepend the cv:: keyword before everything that comes from OpenCV or after the includes

In the C++ interface we have mostly Mat objects. These objects may be freely converted to both IplImage and CvMat with simple assignment.

Mat I;
IplImage pI = I;
CvMat    mI = I;

Now if you want pointers the conversion gets just a little more complicated. The compilers can no longer automatically determinate what you want and as you need to explicitly specify your goal.

Mat I;
IplImage* pI     = &I.operator IplImage();
CvMat* mI        =  &I.operator CvMat();

使用C语言结构,要注意内存泄漏的问题

This will automatically release the object when it’s no longer in use. To use this declare the pointers as a specialization of the Ptr :

Ptr<IplImage> piI = &I.operator IplImage();
 
将旧版本的结构转换成新版本的Mat,在构造方法中进行
Mat K(piL), L;
L = Mat(pI);

vector<Mat> planes;       split(I_YUV, planes);    拆分通道

使用迭代器来遍历各个像素点

MatIterator_<uchar> it = planes[0].begin<uchar>(),

it_end = planes[0].end<uchar>();

for(; it != it_end; ++it)
    {
        double v = *it * 1.7 + rand()%21 - 10;
        *it = saturate_cast<uchar>(v*v/255);
    }

randn(noisyI, Scalar::all(128), Scalar::all(20));  高斯噪声分布

randu() for uniformly distributed random number generation  均匀分布

GaussianBlur(noisyI, noisyI, Size(3, 3), 0.5, 0.5);  高斯模糊

addWeighted(planes[0], contrast_gain, noisyI, 1, -128 + brightness_gain, planes[0]);

图像加权

merge(planes, I_YUV);

不同通道合并

 
注意:
Ptr<IplImage> IplI = cvLoadImage(imagename); 安全指针
cvtColor(I, I_YUV, COLOR_BGR2YCrCb); 转换颜色空间
 
 
 
ALL  Code
#include "stdafx.h"

#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
#define DEMO_MIXED_API_USE

int main( int argc, char** argv )
{
	help(argv[0]);
	const char* imagename = argc > 1 ? argv[1] : "lena.jpg";

#ifdef DEMO_MIXED_API_USE
	Ptr<IplImage> IplI = cvLoadImage(imagename);      // Ptr<T> is safe ref-counting pointer class  // Ptr<IplImage>
	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.
#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);

	vector<Mat> planes;    // Use the STL‘s vector structure to store multiple Mat objects // 使用STL结构来存放各个通道
	split(I_YUV, planes);  // split the image into separate color planes (Y U V) // 拆分通道

#if 1 // change it to 0 if you want to see a blurred and noisy version of this processing
	// Mat scanning
	// Method 1. process Y plane using an iterator
	MatIterator_<uchar> it = planes[0].begin<uchar>(), it_end = planes[0].end<uchar>();	// 使用迭代的方法
	for(; it != it_end; ++it)
	{
		double v = *it * 1.7 + rand()%21 - 10;
		*it = saturate_cast<uchar>(v*v/255);
	}

	for( int y = 0; y < I_YUV.rows; y++ )
	{
		// Method 2. process the first chroma plane using pre-stored row pointer.
		uchar* Uptr = planes[1].ptr<uchar>(y);
		for( int x = 0; x < I_YUV.cols; x++ )
		{
			Uptr[x] = saturate_cast<uchar>((Uptr[x]-128)/2 + 128);

			// Method 3. process the second chroma plane using individual element access
			uchar& Vxy = planes[2].at<uchar>(y, x);
			Vxy =        saturate_cast<uchar>((Vxy-128)/2 + 128);
		}
	}

#else

	Mat noisyI(I.size(), CV_8U);           // Create a matrix of the specified size and type

	// Fills the matrix with normally distributed random values (around number with deviation off).
	// There is also randu() for uniformly distributed random number generation
	randn(noisyI, Scalar::all(128), Scalar::all(20));

	// blur the noisyI a bit, kernel size is 3x3 and both sigma‘s are set to 0.5
	GaussianBlur(noisyI, noisyI, Size(3, 3), 0.5, 0.5);

	const double brightness_gain = 0;
	const double contrast_gain = 1.7;

#ifdef DEMO_MIXED_API_USE
	// To pass the new matrices to the functions that only work with IplImage or CvMat do:
	// step 1) Convert the headers (tip: data will not be copied).
	// step 2) call the function   (tip: to pass a pointer do not forget unary "&" to form pointers)

	IplImage cv_planes_0 = planes[0], cv_noise = noisyI;
	cvAddWeighted(&cv_planes_0, contrast_gain, &cv_noise, 1, -128 + brightness_gain, &cv_planes_0);
#else
	addWeighted(planes[0], contrast_gain, noisyI, 1, -128 + brightness_gain, planes[0]);
#endif

	const double color_scale = 0.5;
	// Mat::convertTo() replaces cvConvertScale.
	// One must explicitly specify the output matrix type (we keep it intact - planes[1].type())
	planes[1].convertTo(planes[1], planes[1].type(), color_scale, 128*(1-color_scale));

	// alternative form of cv::convertScale if we know the datatype at compile time ("uchar" here).
	// This expression will not create any temporary arrays ( so should be almost as fast as above)
	planes[2] = Mat_<uchar>(planes[2]*color_scale + 128*(1-color_scale));

	// Mat::mul replaces cvMul(). Again, no temporary arrays are created in case of simple expressions.
	planes[0] = planes[0].mul(planes[0], 1./255);
#endif

	merge(planes, I_YUV);                // now merge the results back
	cvtColor(I_YUV, I, CV_YCrCb2BGR);  // and produce the output RGB image

	namedWindow("image with grain", WINDOW_AUTOSIZE);   // use this to create images

#ifdef DEMO_MIXED_API_USE
	// this is to demonstrate that I and IplI really share the data - the result of the above
	// processing is stored in I and thus in IplI too.
	cvShowImage("image with grain", IplI);
#else
	imshow("image with grain", I); // the new MATLAB style function show
#endif
	waitKey();

	// Tip: No memory freeing is required!
	//      All the memory will be automatically released by the Vector<>, Mat and Ptr<> destructor.
	return 0;
}
时间: 2024-12-07 14:44:20

OpenCV Tutorials —— Interoperability with OpenCV 1的相关文章

学习opencv tutorials

1.opencv里头动态库和静态库的区别 lib是动态库,staticlib是静态库. 这是opencv tutorials中对动态库和静态库的说明.动态库是在runtime时候才load的库文件.而静态库文件会在你build的时候build-in inside your exe file.优点是可以避免误删,缺点是应用程序变大,加载时间也会变长. 2.  Visual Studio中solution和project的关系 在VS中,一个solution中可以包含多个project. 3.  两

QT+opencv学习笔记一 opencv配置及Mat浅拷贝

今天终于把Qt + opencv配置成功了,中间有一些曲折,在这里记录一下. vs2013 + opencv的方法之前记录过,但这次的不太一样,我们一开始按照这篇文章配置pro Qt5中进行OpenCV开发教程 但是,死活出不来结果,研究发现,我们用的是 mingw 不是 vs,这个方法适合vs编译器 (具体可以参考:win7下的Qt环境+OpenCV视觉库) 后来,我们找到了这篇文章 QT creator+OpenCV2.4.2+MinGW 在windows下开发环境配置 但是还是有点曲折,

【OpenCV入门教程之一】 安装OpenCV:OpenCV 3.0、OpenCV 2.4.8、OpenCV 2.4.9 +VS 开发环境配置

本系列文章由@浅墨_毛星云 出品.   文章链接:http://blog.csdn.net/poem_qianmo/article/details/19809337 1.下载和安装OpenCV SDK VS2010不用说,肯定都安装了吧.来说说当前最新的OpenCV版本2.4.8(2014年2月24日),2.4.9 (2014年4月)的下载和安装.与其说是安装,不如叫解压更加合适,因为我们下载的exe安装文件就是一个自解压程序而已. 在官网:http://opencv.org/上找到OpenCV

Learning OpenCV Lecture 1 (Using OpenCV in VS2010)

1.Create a new Win32 Console Application 2.Open the Property Manager by View->Property Manage r In Visual C++ 2010, a property sheet is an XML file that describes your project settings. We will now create a new one by right-clicking on the Debug | Wi

安装OpenCV:OpenCV 3.0、OpenCV 2.4.8、OpenCV 2.4.9 +VS 开发环境配置

本系列文章由@浅墨_毛星云 出品,转载请注明出处.   文章链接:http://blog.csdn.net/poem_qianmo/article/details/19809337 作者:毛星云(浅墨)    微博:http://weibo.com/u/1723155442 邮箱: [email protected] 知乎:http://www.zhihu.com/people/mao-xing-yun 写作当前博文时配套使用的OpenCV版本: 2.4.8.2.4.9.3.0   ( 2014

[OpenCV][ARM9下移植OpenCV]

安装环境 宿主机: Red Hat Enterprise Linux Server 6.3 开发板: mini2440 相关软件: cmake-3.5.1.tar.gz.OpenCV-2.3.1a.tar.bz2 下载地址: CMake: https://cmake.org/files/v3.5/cmake-3.5.1.tar.gz OpenCV: http://downloads.sourceforge.net/project/opencvlibrary/opencv-unix/2.3.1/O

OpenCV Tutorials &mdash;&mdash; Hough Line Transform

霍夫直线变换 -- 用于检测图像中的直线 利用图像空间和Hough参数空间的点--直线对偶性,把图像空间中的检测问题转换到参数空间,通过在参数空间进行简单的累加统计,然后在Hough参数空间中寻找累加器峰值的方法检测直线 Standard and Probabilistic Hough Line Transform OpenCV implements two kind of Hough Line Transforms: The Standard Hough Transform It consis

OpenCV Tutorials &mdash;&mdash; Feature Matching with FLANN

Extractors of keypoint descriptors in OpenCV have wrappers with a common interface that enables you to easily switch between different algorithms solving the same problem.   DescriptorExtractor::compute Computes the descriptors for a set of keypoints

OpenCV Tutorials &mdash;&mdash; Creating a video with OpenCV

写video 需要用到 VideoWriter  视频文件可看作一个容器 视频的类型由视频文件的后缀名来指定   Due to this OpenCV for video containers supports only the avi extension, its first version. A direct limitation of this is that you cannot save a video file larger than 2 GB. Furthermore you ca