0

I have cv::Mat and my custom struct that holds the data. Is it safe to pass the data from cv::Mat to my structure like this?

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. I also dont want to create copy, since the data may be quite large.

Or is there any other way?

Martin Perry
  • 9,232
  • 8
  • 46
  • 114

1 Answers1

0
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.

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.

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.

Andrey Smorodov
  • 10,649
  • 2
  • 35
  • 42
  • Yes, but I need to get raw data out of `cv::Mat` and assign them to my own struct without copy and without data being destroyed by opencv. I as looking to custom memory allocator for OpenCV matrix, but its quite complex. – Martin Perry Jul 24 '21 at 10:36
  • Problem with passing prealocated memory is that I dont know the size of `imread` result. – Martin Perry Jul 24 '21 at 10:47
  • 1
    You can try manually increase MyMat.u.refcount and matrix data should not be deallocated. But you need to manage it manually, – Andrey Smorodov Jul 24 '21 at 10:55