J. *_*eja 50

在文档上:

http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat

它说:

(...)如果您知道矩阵元素类型,例如它是浮点数,那么您可以使用<>()方法

也就是说,您可以使用:

Mat M(100, 100, CV_64F);
cout << M.at<double>(0,0);
Run Code Online (Sandbox Code Playgroud)

也许这个Mat_课程更容易使用.它是一个模板包装器Mat. Mat_operator()重载,以访问元素.

  • @sumit at <>()方法返回对元素的引用.您可以使用:M.at <double>(0,0)= value; (5认同)
  • 如果我不知道“垫子”的类型怎么办? (2认同)

Mir*_*san 10

上面提供的想法很好.为了快速访问(如果您想要实时应用程序),您可以尝试以下方法:

//suppose you read an image from a file that is gray scale
Mat image = imread("Your path", CV_8UC1);
//...do some processing
uint8_t *myData = image.data;
int width = image.cols;
int height = image.rows;
int _stride = image.step;//in case cols != strides
for(int i = 0; i < height; i++)
{
    for(int j = 0; j < width; j++)
    {
        uint8_t val = myData[ i * _stride + j];
        //do whatever you want with your value
    }
}
Run Code Online (Sandbox Code Playgroud)

指针访问比Mat.at <>访问快得多.希望能帮助到你!

  • 指针访问成本与Mat.at <>(在发布时编译时)完全相同.唯一的区别是断言,除非代码是在调试模式下编译的,否则它们是活动的. (3认同)

WY *_*Hsu 7

基于什么@J。Calleja说,你有两个选择

方法 1 - 随机访问

如果你想随机访问 Mat 的元素,只需简单地使用

Mat.at<data_Type>(row_num, col_num) = value;
Run Code Online (Sandbox Code Playgroud)

方法 2 - 连续访问

如果你想连续访问,OpenCV提供了兼容的Mat迭代器STL iterator,它的C++风格更

MatIterator_<double> it, end;
for( it = I.begin<double>(), end = I.end<double>(); it != end; ++it)
{
    //do something here
}
Run Code Online (Sandbox Code Playgroud)

或者

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
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您对方法2的工作原理有任何理解上的困难,我借用C中动态二维数组一文中的博客文章中的图片,它更加直观和易于理解。

见下图。

在此处输入图片说明