title: Opencv Mat memory management
body: <p>Memory management is essential for an image class. In opencv, the image class is <code>cv::Mat</code>, which has a delicate memory management scheme. Suppose I already have my own image class <code>SelfImage</code>:</p>
  
  <pre><code>class SelfImage
  {
    public:
      int width_;
      int height_;
      unsigned char *pPixel_;    
  };
  </code></pre>
  
  <p>At the beginning, I will put all the image pixel contents to this class:</p>
  
  <pre><code>SelfImage myImage;
  myImage.width_ = 300;
  myImage.height_ = 200;
  myImage.pPixel_ = new [300*200];
  for(int i=0; i&lt;300*200; i++)
        myImage.pPixel_[i] = i%200;
  </code></pre>
  
  <p>Then my question is how I can transform this class to <code>cv::Mat</code> in a very efficient way, one solution I have is:</p>
  
  <pre><code>  cv::Mat mat;
      mat.create( myImage.height_, myImage.width_, CV_8UC1);
      mat.data = myImage.pPixel_;
  </code></pre>
  
  <p>I do not know whether this is a good solution. If <code>cv::Mat::create</code> function will also allocate memory,then the above codes have the danger of memory leak. Any ideas?</p>
  
  <p><strong>EDIT</strong>
    I have to make it clear that it would be nice if I can use <code>cv::Mat::create</code> method but share the memory with <code>SelfImage</code> class.The reason is that a function is defined to perfom the image class transform job <code>void TransImageType(const SelfImage &amp;geo_img, cv::Mat &amp;mat)</code>;  </p>