Convert Mat to vector and Vector to mat in opencv

前端 未结 2 1685
醉话见心
醉话见心 2020-12-18 08:16

i want to Convert Mat to vector and Vector to mat in opencv .

my code :

     void mat_to_vector(Mat in,vector &out){

        for          


        
相关标签:
2条回答
  • 2020-12-18 08:50

    I think my code will be useful for you:

    // Generate some test data
    int r=3;
    int c=3;
    Mat M(r,c,CV_32FC1);
    for(int i=0;i<r*c;++i)
    {
        M.at<float>(i)=i;
    }
    // print out matrix
    cout << M << endl;
    
    // Create vector from matrix data (data with data copying)
    vector<float> V;
    V.assign((float*)M.datastart, (float*)M.dataend);
    
    // print out vector
    cout << "Vector" << endl;
    for(int i=0;i<r*c;++i)
    {
        cout << V[i] << endl;
    }
    
    // Create matrix from vector
    
    // Without copying data (only pointer assigned)
    //Mat M2=Mat(r,c,CV_32FC1,(float*)V.data());
    
    // With copying data
    Mat M2=Mat(r,c,CV_32FC1);
    memcpy(M2.data,V.data(),V.size()*sizeof(float));
    
    
    // Print out matrix created from vector
    cout << "Second matrix" << endl;
    cout << M2 <<endl;
    // wait for a key
    getchar();
    
    0 讨论(0)
  • 2020-12-18 09:13

    This is how I do it. The first function is inspired by https://stackoverflow.com/a/26685567 . The output of VectorToMat is in CV _8U.

    void MatToVector(const Mat& in, vector<float>& out) 
    // Convert a 1-channel Mat<float> object to a vector. 
    {
    if (in.isContinuous()) { out.assign((float*)in.datastart, (float*)in.dataend); }
                    else {   
                    for (int i = 0; i < in.rows; ++i) 
                    { out.insert(out.end(), in.ptr<float>(i), in.ptr<float>(i) + in.cols); }
                    }     return;
    }
    
    
    void VectorToMat(const vector<float>& in,  Mat& out)    
    {
    vector<float>::const_iterator it = in.begin();
    MatIterator_<uchar> jt, end;
    jt = out.begin<uchar>();
    for (; it != in.end(); ++it) { *jt++ = (uchar)(*it * 255); } 
    }
    
    0 讨论(0)
提交回复
热议问题