Ask Your Question
0

template initialization of opencv Mat from 2dVector

asked 2013-01-12 03:13:54 -0600

TSL_ gravatar image

Hi,

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!

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2013-01-13 02:49:30 -0600

Michael Burdinov gravatar image

It is not possible to initialize Mat with vector of vectors. Main reason is that by default Mat(vector) does not perform copy of data. This is just a header that points to contents of the vector itself. It can be done because content of vector is continious in memory. This can't be done with vector of vectors because content of each sub-vector may be in different place in memory and so it must be copied in order to create Mat.

It is possible to initailize Mat with NumType as long as it is legal type for Mat:

Mat_<NumType> mtx(vect.size(),vect[0].size());

Also more effective way of coping data to mtx is:

for(int i=0; i<vect.size(); i++)
{     
    if (vect[0].size() != vect[i].size())
         // throw some error        
    memcpy(mtx.ptr(i), &(vect[i][0]), vect[i].size()*sizeof(NumType));   
}
edit flag offensive delete link more

Question Tools

Stats

Asked: 2013-01-12 03:13:54 -0600

Seen: 978 times

Last updated: Jan 13 '13