繁体   English   中英

将Mat转换为vector <float>,将<float>转换为opencv中的mat

[英]Convert Mat to vector <float> and Vector<float> to mat in opencv

我想在Opencv中将Mat转换为vector并将Vector转换为mat。

我的代码:

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

以上代码很慢。 有更快的解决方案吗?

我认为我的代码对您有用:

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

我就是这样做的。 第一个功能的灵感来自https://stackoverflow.com/a/26685567 VectorToMat的输出在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); } 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM