I'm writing a function with some lines to convert from a 2d STL vector to OpenCV Mat. Since, OpenCV supports Mat initialization from vector with Mat(vector). But this time, I try a 2D vector and not successful.

the function is simple like:

template <class NumType>
Mat Vect2Mat(vector<vector<NumType>> vect)
{
    Mat mtx = Mat(vect.size(), vect[0].size(), CV_64F, 0);  // don't need to init??
    //Mat mtx;

    // copy data
    for (int i=0; i<vect.size(); i++)
        for (int j=0; j<vect[i].size(); j++)
        {
            mtx.at<NumType>(i,j) = vect[i][j];
            //cout << vect[i][j] << " ";
        }   

    return mtx;
}

So is there a way to initalize Mat mtx accordingly with NumType?? the syntax is always fixed with CV_32F, CV_64F, .... and therefore, very restricted

Thank you!

有帮助吗?

解决方案

I think I've found the answer which is given from OpenCV documentation. They call the technique "Class Trait" by the use of DataType class.

it's like:

Mat mtx = Mat::zeros(vect.size(), vect[0].size(), DataType<NumType>::type);

For example:

  template <class NumType>
cv::Mat Vect2Mat(std::vector<std::vector<NumType>> vect)
{
    cv::Mat mtx = cv::Mat::zeros(vect.size(), vect[0].size(), cv::DataType<NumType>::type);  
    //Mat mtx;

    // copy data
    for (int i=0; i<vect.size(); i++)
        for (int j=0; j<vect[i].size(); j++)
        {
            mtx.at<NumType>(i,j) = vect[i][j];
            //cout << vect[i][j] << " ";
        }   

        return mtx;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top