Access to the matrix element in the Mat object (and not in the CvMat object) in OpenCV C ++

How to access elements by line, col in the new "Mat" class of OpenCV 2.0? The documentation is linked below, but I could not understand it. http://opencv.willowgarage.com/documentation/cpp/basic_structures.html#mat

+22
c ++ matrix opencv
Dec 04 '09 at 3:55
source share
4 answers

In the documentation:

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

It says:

(...) if you know a matrix element of a type, for example. it floats, then you can use the <> () method

That is, you can use:

Mat M(100, 100, CV_64F); cout << M.at<double>(0,0); 

It may be easier to use the Mat_ class. This is the template wrapper for Mat . Mat_ has operator() overloaded to access elements.

+44
Dec 04 '09 at 11:23
source share

The ideas presented above are good. For quick access (in case you want to make the application in real time), you can try the following:

 //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 } } 

Accessing pointers is much faster than accessing Mat.at <>. Hope this helps!

+9
Aug 17 '15 at 11:26
source share

OCV does its best to make sure you cannot do this without knowing the type of element, but if you want an easy-to-code, but not very efficient way to read its type-agnostically, you can use something like

 double val=mean(someMat(Rect(x,y,1,1)))[channel]; 

To do this well, you need to know the type. The at <> method is a safe way, but direct access to the data pointer is usually faster if you do it right.

+1
Mar 17 '15 at 5:39
source share

Based on what @J. Calleja said you have two options

Random access

If you want to randomly access a Mat element, just use

 at<data_Type>(row_num, col_num) = value; 

Continuous access

If you want continuous access, OpenCV provides a Mat iterator compatible with the STL iterator

 MatIterator_<double> it, end; for( it = I.begin<double>(), end = I.end<double>(); 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 } } 

I take a picture from a blog post Dynamic two-dimensional arrays in C

enter image description here

0
Oct 27 '17 at 1:46 on
source share



All Articles