opencvvectormat

How to initialize a cv::Mat using a vector of floats?


Is there a way of initializing a opencv cv::Mat using a vector<float> object? Or do I need to loop over every entry of the vector and write it into the cv::Mat object?


Solution

  • I wrote the following test code ( including @Miki 's comment ) to myself to understand in detail.

    you will understand well when you test it.

    #include <opencv2/core.hpp>
    #include <iostream>
    
    using namespace cv;
    using namespace std;
    
    int main(int, char*)
    {
    vector<float> vec{0.1,0.9,0.2,0.8,0.3,0.7,0.4,0.6,0.5,1};
    
    Mat m1( vec ); 
    Mat m2( 1,(int)vec.size(), CV_32FC1,vec.data() );
    Mat1f m3( (int)vec.size(), 1, vec.data() );
    Mat1f m4( 1, (int)vec.size(), vec.data() );
    
    Mat m5{vec, false}; // see Jean-Christophe's answer
    
    cout << "as seen below all Mat and vector use same data" << endl;
    cout << vec[0] << endl;
    m1 *= 2;
    cout << vec[0] << endl;
    m2 *= 2;
    cout << vec[0] << endl;
    m3 *= 2;
    cout << vec[0] << endl;
    m4 *= 2;
    cout << vec[0] << endl;
    m5 *= 2;
    cout << vec[0] << endl;
    
    return 0;
    }