0

I want to write a short function to display OpenCV Mat matrix type. I'm closed to finish it. This is my code:

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

is there any way that I can get around this to have a compact and channel num free display function???

Sam
  • 19,708
  • 4
  • 59
  • 82
TSL_
  • 2,049
  • 3
  • 34
  • 55

1 Answers1

1

What about this?

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

Anyway, your code is much easier if you use 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;
    }
}
Sam
  • 19,708
  • 4
  • 59
  • 82
  • thank you for a good hint! I've just learnt it. What about a little more beautiful output format?? – TSL_ Aug 29 '12 at 13:35
  • There are some modifiers for the output, but I cannot remember them. You can format it Matlab-style, C-style, and I think XML-style. It's somewhere in the docs... – Sam Aug 29 '12 at 13:36
  • can this also be applied for CvMat and InputArray or OutputArray?? other versions of matrix in OpenCV?? – TSL_ Aug 29 '12 at 13:39
  • InputArray and outputArrat have a getMat() method that converts them to Mat. CvMat should also be easy to convert to Mat, but a direct flush to cout is not possible – Sam Aug 29 '12 at 13:43
  • 1
    thank you a lot! hope you willstop by if I have problems with the output formatting :D – TSL_ Aug 29 '12 at 13:47