在OpenCV中,将Mat转换为<float>向量和将<float>向量转换为Mat的方法

4
我想在OpenCV中将Mat转换为向量和向量转换为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));
            }
        }
}

上述代码运行较慢。 是否有更快的解决方案?
2个回答

9
我认为我的代码对你会有用:

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

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

有没有其他的解决方案可以将vector<float>转换为Mat类型,且指定cols和rows的大小? - user3088563
你可以使用这个构造函数:template<typename T, int n> explicit Mat::Mat(const Vec<T, n>& vec, bool copyData=true) - Rosa Gronchi
出现了问题: 向量是一维的。而已经被推入的是二维矩阵。 解决方案是什么? - user3088563
看这个函数: 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(); } } } - user3088563
1
似乎还需要检查m.isContinuous() - mrgloom
显示剩余2条评论

1

这是我的做法。第一个函数受到 https://dev59.com/fF8d5IYBdhLWcg3wkS0V#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); } 
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接