How to convert C++ array to opencv Mat

前端 未结 1 368
我寻月下人不归
我寻月下人不归 2020-12-29 11:39

What is the fastest way to convert a C++ array into an 2D opencv Mat object? Brute force method would be to loop over all entries of the 2D mat and fill them with values of

相关标签:
1条回答
  • 2020-12-29 11:53

    Yes there is, in the documentation of cv::Mat you can see how it can be achieved.

    Specifically in this line

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

    This means that you can do something like

    double x[100][100];
    
    cv::Mat A(100, 100, CV_64F, x);
    

    This will not copy the data to it. You have to also remember that OpenCV data is row major, which means that it has all the columns of one rows and then the next row and so on. So your array has to match this style for it to work.

    About how fast it is, the documentation also talks about it:

    data – 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.

    It will work quite fast, but it is the same array, if you modified it outside of the cv::Mat, it will be modified in the cv::Mat, and if it is destroyed at any point, the data member of cv::Mat will point to a non-existant place.

    UPDATE:

    I forgot to also say, that you can create the cv::Mat and do std::memcpy. This way it will copy the data, which may be slower, but the data will be owned by the cv::Mat object and destroyed upon with the cv::Mat destroyer.

    double x[100][100];
    cv::Mat A(100,100,CV_64F);
    std::memcpy(A.data, x, 100*100*sizeof(double));
    
    0 讨论(0)
提交回复
热议问题