Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
921 views
in Technique[技术] by (71.8m points)

c++ - Convert Mat to vector <float> and Vector<float> to mat in opencv

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

my code :

     void mat_to_vector(Mat in,vector<float> &out){

        for (int i=0; i < in.rows; i++) {
             for (int j =0; j < in.cols; j++){
                //unsigned char temp;

                //file << Dst.at<float>(i,j)  << endl;
                 out.push_back(in.at<float>(i,j));
            }
        }

    }
void vector_to_mat(vector<float> in, Mat out,int cols , int rows){
    for (int i=rows-1; i >=0; i--) {
             for (int j =cols -1; j >=0; j--){

                 out.at<float>(i,j) = in.back();
                 in.pop_back();
                //file << Dst.at<float>(i,j)  << endl;
                // dst_temp.push_back(Dst.at<float>(i,j));
            }
        }
}

Above codes are slow. are there faster solutions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...