简体   繁体   中英

OpenCV vector of vectors into cv::Mat

I have certain values in an std::vector<std::vector<double>> structure of n rows and m cols which I would like to convert into an equivalent cv::Mat object. This is the code I have been using but I'm getting an error:

dctm is a local argument which is defined as: std::vector<std::vector<double>>

cv::Mat dctmat = cvCreateMat(dctm.size(), dctm[0].size(), CV_16SC1);
for (size_t i = 0; i < dctm.size(); i++) {
    for (size_t j = 0; j < dctm[i].size(); j++) {
        dctmat.at<double>(i, j) = dctm[i][j];
    }
}

dctmat has a type CV_16SC1 which means matrix of signed short. But you try to access it with dctmat.at<double>(i, j) which is incoherent. Either define your matrix as CV_64FC1 or access it with dctmat.at<short>(i, j) (first solution is better because you have a vector of double ).

Here is my templated version of conversion routines

routines

template<typename _Tp> static  cv::Mat toMat(const vector<vector<_Tp> > vecIn) {
    cv::Mat_<_Tp> matOut(vecIn.size(), vecIn.at(0).size());
    for (int i = 0; i < matOut.rows; ++i) {
        for (int j = 0; j < matOut.cols; ++j) {
            matOut(i, j) = vecIn.at(i).at(j);
        }
    }
    return matOut;
}
template<typename _Tp> static  vector<vector<_Tp> > toVec(const cv::Mat_<_Tp> matIn) {
    vector<vector<_Tp> > vecOut(matIn.rows);
    for (int i = 0; i < matIn.rows; ++i) {
        vecOut[i].resize(matIn.cols);
        for (int j = 0; j < matIn.cols; ++j) {
            vecOut[i][j] =  matIn.at<_Tp>(i, j);
        }
    }
    return vecOut;
}

Here in the Opencv documentation you can found this:

Mat::Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP)
Mat::Mat(Size size, int type, void* data, size_t step=AUTO_STEP)
...

then, you can use like this:

Mat dctmat(dctm.size(), dctm[0].size(), CV_16SC1, dctm.data());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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