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.willowgarage.com/documentation/cpp/basic_structures.html#mat
A faster way [1] to access matrix elements is to use also the member function . ptr which works as a classic pointer style access, returning the pointer to the specific row. As the function cv::Mat::ptr returns the pointer to the row, we have to go through the other dimensions from that point running through pointers.
The Mat class of OpenCV library is used to store the values of an image. It represents an n-dimensional array and is used to store image data of grayscale or color images, voxel volumes, vector fields, point clouds, tensors, histograms, etc.
Here's example for CV_64FC1 : CV_ - this is just a prefix. 64 - number of bits per base matrix element (e.g. pixel value in grayscale image or single color element in BGR image) F - type of the base element.
so CV_8UC3 is an 8-bit unsigned integer matrix/image with 3 channels. Although it is most common that this means an RGB (or actually BGR) image, it does not mandate it. It simply means that there are three channels, and how you use them is up to you and your application.
On the documentation:
http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat
It says:
(...) if you know the matrix element type, e.g. it is float, then you can use at<>() method
That is, you can use:
Mat M(100, 100, CV_64F); cout << M.at<double>(0,0);
Maybe it is easier to use the Mat_
class. It is a template wrapper for Mat
. Mat_
has the operator()
overloaded in order to access the elements.
The ideas provided above are good. For fast access (in case you would like to make a real time application) you could 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 } }
Pointer access is much faster than the Mat.at<> accessing. Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With