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

前端 未结 5 1022
有刺的猬
有刺的猬 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

    Based on what @J. Calleja said, you have two choices

    Method 1 - Random access

    If you want to random access the element of Mat, just simply use

    Mat.at(row_num, col_num) = value;
    

    Method 2 - Continuous access

    If you want to continuous access, OpenCV provides Mat iterator compatible with STL iterator and it's more C++ style

    MatIterator_ it, end;
    for( it = I.begin(), end = I.end(); it != end; ++it)
    {
        //do something here
    }
    

    or

    for(int row = 0; row < mat.rows; ++row) {
        float* p = mat.ptr(row); //pointer p points to the first place of each row
        for(int col = 0; col < mat.cols; ++col) {
             *p++;  // operation here
        }
    }
    

    If you have any difficulty to understand how Method 2 works, I borrow the picture from a blog post in the article Dynamic Two-dimensioned Arrays in C, which is much more intuitive and comprehensible.

    See the picture below.

提交回复
热议问题