How to perform image class transformation with cv::Mat?

asked 2014-04-23 10:26:01 -0600

feelfree gravatar image

updated 2019-10-13 14:06:55 -0600

Memory management is essential for an image class. In opencv, the image class is cv::Mat, which has a delicate memory management scheme. Suppose I already have my own image class SelfImage:

class SelfImage
{
  public:
    int width_;
    int height_;
    unsigned char *pPixel_;    
};

At the beginning, I will put all the image pixel contents to this class:

SelfImage myImage;
myImage.width_ = 300;
myImage.height_ = 200;
myImage.pPixel_ = new [300*200];
for(int i=0; i<300*200; i++)
      myImage.pPixel_[i] = i%200;

Then my question is how I can transform this class to cv::Mat in a very efficient way, one solution I have is:

  cv::Mat mat;
    mat.create( myImage.height_, myImage.width_, CV_8UC1);
    mat.data = myImage.pPixel_;

I do not know whether this is a good solution. If cv::Mat::create function will also allocate memory,then the above codes have the danger of memory leak. Any ideas? Thanks.

edit retag flag offensive close merge delete