Search code examples
c++opencvmat

Print multidimensional Mat in OpenCV (C++)


In the OpenCV Tutorial

http://docs.opencv.org/master/d6/d6d/tutorial_mat_the_basic_image_container.html

is the following example for creating a Mat.

int sz[3] = {2,2,2};
Mat L(3,sz, CV_8UC(1), Scalar::all(0));

This works fine, but when i try to print the Mat my programm crashes.

cout << "L = " << endl << " " << L << endl << endl;

Why doesn't this work ? Is there a way to do this without loops or splitting the Mat L ?


Solution

  • To print n-dim matrix you could use Matrix slice. Since 2d matrices are stored row by row, 3d matrices plane by plane and so on, you could use code:

    cv::Mat sliceMat(cv::Mat L,int dim,std::vector<int> _sz)
    {
    cv::Mat M(L.dims - 1, std::vector<int>(_sz.begin() + 1, _sz.end()).data(), CV_8UC1, L.data + L.step[0] * 0);
    return M;
    }
    

    To perform mat slice.For more dimensions you should make more slices. Example shows 3 and 4 dimension matrices:

    std::cout << "3 dimensions" << std::endl;
    
    std::vector<int> sz = { 3,3,3 };
    
    cv::Mat L;
    L.create(3, sz.data(), CV_8UC1);
    L = cv::Scalar(255);
    
    std::cout<< sliceMat(L, 1, sz);
    
    std::cout << std::endl;
    std::cout <<"4 dimensions"<< std::endl;
    sz = { 5,4,3,5 };
    L.create(4, sz.data(), CV_8UC1);
    L = cv::Scalar(255);
    std::cout << sliceMat(sliceMat(L, 1, sz),2, std::vector<int>(sz.begin() + 1, sz.end()));
    

    end result screen

    enter image description here