我如何通过像素数据的所有权CV ::垫 [英] How do I pass ownership of pixel data to cv::Mat

查看:157
本文介绍了我如何通过像素数据的所有权CV ::垫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个简历::垫传递与我有外部划分像素数据。

I am creating a cv::Mat passing with pixel data that I have allocated externally.

cv::Mat myMatrix(vImageResult.height,
                 vImageResult.width,
                 CV_8UC1,
                 vImageResult.data);

我想CV ::垫采取字节的所有权(即,当它达到零创建一个引用计数和自由的字节)。然而,文档说:

矩阵构造函数,拿数据和步骤参数不分配矩阵数据。相反,它们只是初始化矩阵头指向指定的数据,这意味着,没有数据被复制。这种操作是非常有效的,并且可以被用来处理使用OpenCV函数外部数据。 外部数据不会自动释放,所以你应该照顾它。

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.


  • 如果我释放潜在的 vImageResult.data 随即,我将得到一个坏访问崩溃某处就行了。

  • 如果我不释放潜在的 vImageResult.data 则数据将韭菜。

  • If I free the underlying vImageResult.data immediately, the I will get a bad access crash somewhere down the line.
  • If I don't free the underlying vImageResult.data then the data will leek.
  • 有没有办法通过所有权?

    Is there a way to pass ownership?

    推荐答案

    您不能。

    CV ::垫不知道你是怎么分配的内存(的malloc,新等),因此,不知道如何释放它。

    cv::Mat does not know how you allocated the memory(malloc, new, etc), and hence, does not know how to free it.

    如果你是自己分配的数据,您可以随时拨打 CV ::垫::创建(...)来分配你需要的内存,然后再传递指针 myMatrix.data 来的任何功能,您使用的是加载数据。

    If you are allocating the data yourself, you could always call cv::Mat::create(...) to allocate the memory you need, and then pass the pointer myMatrix.data to whatever function you are using to load the data.

    如果你指的是通过视频捕获流或外部库提供给您pre-分配的内存,你的运气了。

    If you're referring to pre-allocated memory provided to you through a video capture stream or external library, you're out of luck.

    Andreas的解决方案将工作,但如果经常使用可能会很慢。

    Andreas' solution will work, but can be slow if used frequently.

    一个妥协可能是换行 CV ::垫在自己的类型:

    A compromise may be to wrap cv::Mat in your own type:

    struct MyMat
    {
        cv::Mat mat;
        MyMat(int width, int height, int format, char *data)
            : mat(height, width, format, data){}
        ~MyMat() { delete [] mat.data; }
    };
    

    请注意:这是有意要设法子类品种::垫。它没有虚析构函数。

    Note: it was intentional not to try and subclass cv::Mat. It does not have a virtual destructor.

    这篇关于我如何通过像素数据的所有权CV ::垫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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