本文介绍了Opencv Mat内存管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

内存管理对于图像类至关重要。在opencv中,图像类是 cv :: Mat ,它具有精细的内存管理方案。假设我已经拥有自己的图像类 SelfImage

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;

然后我的问题是如何将此类转换为 cv :: Mat 以非常有效的方式,我有一个解决方案:

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_;

我不知道这是否是一个好的解决方案。如果 cv :: Mat :: create 函数也会分配内存,那么上面的代码就有内存泄漏的危险。有什么想法吗?

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?

编辑
我必须明确表示如果我可以使用 cv :: Mat :: create 方法但是用 SelfImage 类共享内存。原因是定义了一个函数来执行图像类转换作业 void TransImageType(const SelfImage& geo_img,cv :: Mat& mat);

EDIT I have to make it clear that it would be nice if I can use cv::Mat::create method but share the memory with SelfImage class.The reason is that a function is defined to perfom the image class transform job void TransImageType(const SelfImage &geo_img, cv::Mat &mat);

推荐答案

cv :: Mat ,您可以在其中指定用户数据:

cv::Mat has a constructor where you can specify user data:

Mat::Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP)

文档说明以下关于数据的参数:

The documentation says the following about the data argument:

这篇关于Opencv Mat内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 18:23