Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

opencv

matrix

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

like image 704
neptune Avatar asked Dec 04 '09 03:12

neptune


People also ask

How do you access the elements of 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.

What is mat object in OpenCV?

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.

What is cv_64f?

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.

What is CV_8UC3?

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.


2 Answers

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.

like image 188
J. Calleja Avatar answered Oct 18 '22 00:10

J. Calleja


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!

like image 34
Mircea Paul Muresan Avatar answered Oct 17 '22 23:10

Mircea Paul Muresan