nep*_*une 30 c++ opencv matrix
如何在OpenCV 2.0的新"Mat"类中按行,列访问元素?文档链接如下,但我无法理解它. http://opencv.willowgarage.com/documentation/cpp/basic_structures.html#mat
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()重载,以访问元素.
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 <>访问快得多.希望能帮助到你!
基于什么@J。Calleja说,你有两个选择
如果你想随机访问 Mat 的元素,只需简单地使用
Mat.at<data_Type>(row_num, col_num) = value;
Run Code Online (Sandbox Code Playgroud)
如果你想连续访问,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中动态二维数组一文中的博客文章中的图片,它更加直观和易于理解。
见下图。