Opencv Mat内存管理 [英] Opencv Mat memory management

查看:395
本文介绍了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函数处理外部数据
。外部数据不是
自动解除分配,所以你应该照顾它。

Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆