OpenCV matrix from vector of vectors without copying data

Is it possible to create cv::Mat

from std::vector<std::vector<T>>

where all vectors are the same width, without copying the data, i.e. creating header only, how could it be for creating cv::Mat

from std::vector<T>

?

I have a wrapper that can only use STL types in the interface and pass them to the core OpenCV functions. I would like to avoid over-converting back and forth.

+3


source to share


2 answers


In general, no. You cannot make any guarantees about the relative memory locations of each internal std :: vector. Cv :: Mat requires all of its memory to be contiguous or have a predictable transition between each line. It only stores one pointer to the beginning of its data, and it needs a pointer for each vector to access your internal vector.



If you can somehow guarantee the continuity of your memory, then yes, you can.

+3


source


If you are really looking for efficiency, you should work based on this constructor:

// C++: 

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

      

This constructor does not copy data in which any inefficiency might occur. Therefore, instead of nested vectors, there is one vector that contains all the data.



Note that the lifetime of the data in your vector must be long enough to access the matrix, which means that you also cannot resize your vector, as this could invalidate the underlying data that are &v[0]

.

If you are allowed to use boost::matrix

in your shared code, this might solve your problem.

+1


source







All Articles