将Mat转换为向量< float>和Vector< float>到opencv中的mat [英] Convert Mat to vector <float> and Vector<float> to mat in opencv
本文介绍了将Mat转换为向量< float>和Vector< float>到opencv中的mat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在opencv中将Mat转换为矢量和矢量到mat。
i want to Convert Mat to vector and Vector to mat in opencv .
我的代码:
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?
推荐答案
我认为我的代码将对你有用:
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();
这篇关于将Mat转换为向量< float>和Vector< float>到opencv中的mat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文