Accessing a matrix element in the “Mat” object (not the CvMat object) in OpenCV C++

前端 未结 5 1020
有刺的猬
有刺的猬 2020-12-08 06:50

How to access elements by row, col in OpenCV 2.0\'s new \"Mat\" class? The documentation is linked below, but I have not been able to make any sense of it. http://opencv.wi

5条回答
  •  孤城傲影
    2020-12-08 07:39

    For cv::Mat_ mat just use mat(row, col)

    Accessing elements of a matrix with specified type cv::Mat_< _Tp > is more comfortable, as you can skip the template specification. This is pointed out in the documentation as well.

    code:

    cv::Mat1d mat0 = cv::Mat1d::zeros(3, 4);
    std::cout << "mat0:\n" << mat0 << std::endl;
    std::cout << "element: " << mat0(2, 0) << std::endl;
    std::cout << std::endl;
    
    cv::Mat1d mat1 = (cv::Mat1d(3, 4) <<
        1, NAN, 10.5, NAN,
        NAN, -99, .5, NAN,
        -70, NAN, -2, NAN);
    std::cout << "mat1:\n" << mat1 << std::endl;
    std::cout << "element: " << mat1(0, 2) << std::endl;
    std::cout << std::endl;
    
    cv::Mat mat2 = cv::Mat(3, 4, CV_32F, 0.0);
    std::cout << "mat2:\n" << mat2 << std::endl;
    std::cout << "element: " << mat2.at(2, 0) << std::endl;
    std::cout << std::endl;
    

    output:

    mat0:
    [0, 0, 0, 0;
     0, 0, 0, 0;
     0, 0, 0, 0]
    element: 0
    
    mat1:
    [1, nan, 10.5, nan;
     nan, -99, 0.5, nan;
     -70, nan, -2, nan]
    element: 10.5
    
    mat2:
    [0, 0, 0, 0;
     0, 0, 0, 0;
     0, 0, 0, 0]
    element: 0
    

提交回复
热议问题