文章标题

来源:互联网 发布:知乎注册不了为什么 编辑:程序博客网 时间:2024/06/08 07:52

Mat 和 CvMat,IplImage相互转化

Now for converting theMatobject you can use either theIplImage or theCvMatoperators. While in the C interface

you used to work with pointers here it’s no longer the case. In the C++ interface we have mostlyMatobjects. These
objects may be freely converted to bothIplImageandCvMatwith simple assignment. For example:
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. This is to call theIplImage andCvMat
operators and then get their pointers. For getting the pointer we use the & sign:
Mat I;
IplImage*pI = &I.operator IplImage();
CvMat*mI = &I.operator CvMat();
One of the biggest complaints of the C interface is that it leaves all the memory management to you. You need to figure
out when it is safe to release your unused objects and make sure you do so before the program finishes or you could
have troublesome memory leeks. To work around this issue in OpenCV there is introduced a sort of smart pointer.
This will automatically release the object when it’s no longer in use. To use this declare the pointers as a specialization
of thePtr:
Ptr<IplImage> piI = &I.operator IplImage();
Converting from the C data structures to theMatis done by passing these inside its constructor. For example:
Mat K(piL), L;

L = Mat(pI);

opencv中的例子

[cpp] view plain copy
print?
  1. #include <stdio.h>  
  2. #include <iostream>  
  3.   
  4.   
  5. #include <opencv2/core/core.hpp>  
  6. #include <opencv2/imgproc/imgproc.hpp>  
  7. #include <opencv2/highgui/highgui.hpp>  
  8.   
  9.   
  10. using namespace cv;  // The new C++ interface API is inside this namespace. Import it.  
  11. using namespace std;  
  12.   
  13.   
  14. void help( char* progName)  
  15. {  
  16.     cout << endl << progName   
  17.         << ” shows how to use cv::Mat and IplImages together (converting back and forth).” << endl   
  18.         << ”Also contains example for image read, spliting the planes, merging back and ”  << endl   
  19.         << ” color conversion, plus iterating through pixels. ”                            << endl  
  20.         << ”Usage:” << endl  
  21.         << progName << ” [image-name Default: lena.jpg]”                           << endl << endl;  
  22. }  
  23.   
  24.   
  25. // comment out the define to use only the latest C++ API  
  26. #define DEMO_MIXED_API_USE   
  27.   
  28.   
  29. int main( int argc, char** argv )  
  30. {  
  31.     help(argv[0]);  
  32.     const char* imagename = argc > 1 ? argv[1] : “lena.jpg”;  
  33.   
  34.   
  35. #ifdef DEMO_MIXED_API_USE  
  36.     Ptr<IplImage> IplI = cvLoadImage(imagename);      // Ptr<T> is safe ref-counting pointer class  
  37.     if(IplI.empty())  
  38.     {  
  39.         cerr << ”Can not load image ” <<  imagename << endl;  
  40.         return -1;  
  41.     }  
  42.     Mat I(IplI); // Convert to the new style container. Only header created. Image not copied.      
  43. #else  
  44.     Mat I = imread(imagename);        // the newer cvLoadImage alternative, MATLAB-style function  
  45.     if( I.empty() )                   // same as if( !I.data )  
  46.     {  
  47.         cerr << ”Can not load image ” <<  imagename << endl;  
  48.         return -1;  
  49.     }  
  50. #endif  
  51.       
  52.     // convert image to YUV color space. The output image will be created automatically.   
  53.     Mat I_YUV;  
  54.     cvtColor(I, I_YUV, CV_BGR2YCrCb);   
  55.   
  56.   
  57.     vector<Mat> planes;    // Use the STL’s vector structure to store multiple Mat objects   
  58.     split(I_YUV, planes);  // split the image into separate color planes (Y U V)  
  59.   
  60.   
  61. #if 1 // change it to 0 if you want to see a blurred and noisy version of this processing  
  62.     // Mat scanning  
  63.     // Method 1. process Y plane using an iterator  
  64.     MatIterator_<uchar> it = planes[0].begin<uchar>(), it_end = planes[0].end<uchar>();  
  65.     for(; it != it_end; ++it)  
  66.     {  
  67.         double v = *it * 1.7 + rand()%21 - 10;  
  68.         *it = saturate_cast<uchar>(v*v/255);  
  69.     }  
  70.       
  71.     forint y = 0; y < I_YUV.rows; y++ )  
  72.     {  
  73.         // Method 2. process the first chroma plane using pre-stored row pointer.  
  74.         uchar* Uptr = planes[1].ptr<uchar>(y);  
  75.         forint x = 0; x < I_YUV.cols; x++ )  
  76.         {  
  77.             Uptr[x] = saturate_cast<uchar>((Uptr[x]-128)/2 + 128);  
  78.               
  79.             // Method 3. process the second chroma plane using individual element access  
  80.             uchar& Vxy = planes[2].at<uchar>(y, x);  
  81.             Vxy =        saturate_cast<uchar>((Vxy-128)/2 + 128);  
  82.         }  
  83.     }  
  84.   
  85.   
  86. #else  
  87.       
  88.     Mat noisyI(I.size(), CV_8U);           // Create a matrix of the specified size and type  
  89.       
  90.     // Fills the matrix with normally distributed random values (around number with deviation off).  
  91.     // There is also randu() for uniformly distributed random number generation  
  92.     randn(noisyI, Scalar::all(128), Scalar::all(20));   
  93.       
  94.     // blur the noisyI a bit, kernel size is 3x3 and both sigma’s are set to 0.5  
  95.     GaussianBlur(noisyI, noisyI, Size(3, 3), 0.5, 0.5);   
  96.   
  97.   
  98.     const double brightness_gain = 0;  
  99.     const double contrast_gain = 1.7;  
  100.   
  101.   
  102. #ifdef DEMO_MIXED_API_USE  
  103.     // To pass the new matrices to the functions that only work with IplImage or CvMat do:  
  104.     // step 1) Convert the headers (tip: data will not be copied).  
  105.     // step 2) call the function   (tip: to pass a pointer do not forget unary ”&” to form pointers)  
  106.       
  107.     IplImage cv_planes_0 = planes[0], cv_noise = noisyI;      
  108.     cvAddWeighted(&cv_planes_0, contrast_gain, &cv_noise, 1, -128 + brightness_gain, &cv_planes_0);  
  109. #else  
  110.     addWeighted(planes[0], contrast_gain, noisyI, 1, -128 + brightness_gain, planes[0]);  
  111. #endif  
  112.       
  113.     const double color_scale = 0.5;  
  114.     // Mat::convertTo() replaces cvConvertScale.   
  115.     // One must explicitly specify the output matrix type (we keep it intact - planes[1].type())  
  116.     planes[1].convertTo(planes[1], planes[1].type(), color_scale, 128*(1-color_scale));  
  117.   
  118.   
  119.     // alternative form of cv::convertScale if we know the datatype at compile time (“uchar” here).  
  120.     // This expression will not create any temporary arrays ( so should be almost as fast as above)  
  121.     planes[2] = Mat_<uchar>(planes[2]*color_scale + 128*(1-color_scale));  
  122.   
  123.   
  124.     // Mat::mul replaces cvMul(). Again, no temporary arrays are created in case of simple expressions.  
  125.     planes[0] = planes[0].mul(planes[0], 1./255);  
  126. #endif  
  127.   
  128.   
  129.       
  130.     merge(planes, I_YUV);                // now merge the results back  
  131.     cvtColor(I_YUV, I, CV_YCrCb2BGR);  // and produce the output RGB image  
  132.   
  133.   
  134.       
  135.     namedWindow(”image with grain”, CV_WINDOW_AUTOSIZE);   // use this to create images  
  136.   
  137.   
  138. #ifdef DEMO_MIXED_API_USE  
  139.     // this is to demonstrate that I and IplI really share the data - the result of the above  
  140.     // processing is stored in I and thus in IplI too.  
  141.     cvShowImage(”image with grain”, IplI);  
  142. #else  
  143.     imshow(”image with grain”, I); // the new MATLAB style function show  
  144. #endif  
  145.     waitKey();  
  146.   
  147.   
  148.     // Tip: No memory freeing is required!   
  149.     //      All the memory will be automatically released by the Vector<>, Mat and Ptr<> destructor.  
  150.     return 0;      
  151. }  
#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;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 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, CV_BGR2YCrCb); vector<Mat> planes; // Use the STL's vector structure to store multiple Mat objects 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", CV_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; }

0 0
原创粉丝点击