2013-01-12 37 views
1

我正在寫一個函數用於將一個2d STL向量轉換爲OpenCV Mat。由於OpenCV支持Mat(向量)從向量進行Mat初始化。但是這一次,我嘗試了一個2D矢量而沒有成功。opencv的模板初始化從矢量的墊子

功能簡單,如:

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

那麼,有沒有辦法與NumType相應initalize墊MTX?語法總是固定在CV_32F,CV_64F,....因此,非常有限

謝謝!

回答

2

我想我找到了從OpenCV文檔中給出的答案。他們通過使用DataType類來調用技術「Class Trait」。

它像:

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

例如:

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; 
} 
+0

+1爲偉大的答案。舉一個例子可能會有所幫助,我在確定要替換的零件時遇到了一些困難。 mat mtx = Mat :: zeros(vect.size(),vect [0] .size(),DataType :: type); – qwerty9967