简体   繁体   English

OpenCV Mat 将数据移动到自定义结构

[英]OpenCV Mat move data to custom structure

I have cv::Mat and my custom struct that holds the data.我有cv::Mat和保存数据的自定义结构。 Is it safe to pass the data from cv::Mat to my structure like this?像这样将数据从cv::Mat传递到我的结构是否安全?

struct MyStruct {
   uint8_t* data;
}

MyStruct foo(){
   MyStruct s;

   cv::Mat m = cv::imread("test.png", 0);
   s.data = m.data;
   m.data = nullptr;

   return s;
}

Basically, I need OpenCV not to destroy allocated cv::Mat data.基本上,我需要 OpenCV 不破坏分配的cv::Mat数据。 I also dont want to create copy, since the data may be quite large.我也不想创建副本,因为数据可能非常大。

Or is there any other way?或者还有其他方法吗?

cv::Mat a,b;
...
b=a;

Will not do a new copy of data.不会做数据的新拷贝。 It will just copy the header and will increase smart pointer counter.它只会复制标题并增加智能指针计数器。

To apply deep copy you need to do:要应用深拷贝,您需要执行以下操作:

b=a.clone();

else data will be shared between a and b.否则数据将在 a 和 b 之间共享。

If you want use custom storage, it's better to allocate and copy explicitely如果要使用自定义存储,最好明确分配和复制
then allow opencv free allocated Mat, else you risk to break memory management in your application.然后允许 opencv 免费分配 Mat,否则您可能会破坏应用程序中的内存管理。

Also you may try to create a matrix using preallocated array:您也可以尝试使用预分配数组创建矩阵:

float my_data[100][100];
cv::Mat A(100, 100, CV_32F, my_data);

But not sure about memory management in this case, can't try it now.但不确定这种情况下的内存管理,现在不能尝试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM