0

我想写一个简短的函数来显示 OpenCV 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;
}

有什么办法可以解决这个问题,以获得紧凑且无通道数的显示功能???

4

1 回答 1

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;
    }
}
于 2012-08-29T13:30:30.950 回答