2012-08-29 33 views
0

我想寫一個簡短的函數來顯示OpenCV Mat矩陣類型。我關閉完成它。這是我的代碼:多通道Mat顯示功能

template <class eleType> 
int MATmtxdisp(const Mat mtx, eleType fk) 
// create function template to avoid type dependent programming i.e. Mat element can be float, Vec2f, Vec3f, Vec4f 
// cannot get rid of fk ('fake') variable to identify Mat element type 
{ 
    uchar chan = mtx.channels(); 

    for(int i = 0; i < mtx.rows; i++) 
     for(int k = 0; k < chan; k++) 
     { 
      for(int l = 0; l < mtx.cols; l++) 
      { 
       eleType ele = mtx.at<eleType>(i,l); 
// I even split 2 cases for 1 channel and multi-channel element 
// but this is unacceptable by the compiler when element is float type (1 channel) 
// i.e. C2109: subscript requires array or pointer type 
       if (chan > 1) 
        printf("%8.2f",ele[k]); 
       else 
        printf("%8.2f",ele); 
      } 
      printf("\n"); 
     } 

     return 0; 
} 

有沒有什麼辦法,我可以解決這個有一個緊湊和通道數量免費的顯示功能?

回答

1

這是怎麼回事?

cv::Mat myMat(2,3, CV_8UC3, cv::Scalar(1, 2, 3)); 
std::cout << myMat << std::endl; 

無論如何,你的代碼是容易得多,如果你使用的cout:

template <class T> 
int MATmtxdisp(const Mat& mtx) 
{ 
    uchar chan = mtx.channels(); 
    int step = mtx.step(); 
    T* ptr = (T*)mtx.data; 

    for(int i = 0; i < mtx.rows; i++) 
     for(int k = 0; k < chan; k++) 
     { 
      for(int l = 0; l < mtx.cols; l++) 
      { 
       cout << ptr[ /* calculate here the index */]; 
      } 
      cout << endl; 
    } 
} 
+0

感謝你一個很好的提示!我剛剛學會了。怎麼樣一個更漂亮的輸出格式? –

+0

輸出有一些修飾符,但我不記得它們。你可以格式化它的Matlab風格,C風格,我認爲XML風格。它在文檔中的某處... – Sam

+0

這也可以應用於CvMat和InputArray或OutputArray? OpenCV中其他版本的矩陣? –