Access to the OpenCV Mat Matrix, which is the fastest for and why?

I am wondering how to access data in Mat in OpenCV. As you know, we can access data in many ways. I want to save an image (width x height x 1-depth) in Mat and looping to access every pixel of the image. Using ptr <> (irow) to get a pixel of a row and then access each column in a row is the best way? or use in <> (irow, jcol) is the best? or using direct index counting using index = irow * Width + jrow is the best? Does anyone know the reason.

Thank you in advance

+4
source share
4 answers

Information here can be found in the documentation: the main image container and how to scan images .

I will advise you to practice with at ( here ) if you are not familiar with OpenCV or with types of languages ​​like hell. But the fastest way is ptr as Nolwenn's answer , because you avoid type checking.

+3
source

I understand that this is an old question, but I think that the current answers are somehow misleading.

A call to both at<T>(...) and ptr<T>(...) will check the bounds in debug mode. If the _DEBUG macro _DEBUG not defined, they will basically compute y * width + x and give you either a pointer to the data or the data itself. Thus, using at<T>(...) in release mode is equivalent to calculating the pointer yourself, but safer because calculating the pointer is not just y * width + x if the matrix is ​​just a sub-representation of another matrix. In debug mode, you get security checks.

I think the best way is to process the image line by line, get the line pointer using ptr<T>(y) , and then using p[x] . This has the advantage that you do not need to calculate with various data layouts and there is still a simple pointer to the inner loop.

You can use simple pointers completely, which would be most efficient because you avoid multiplying by a string, but then you need to use step1(i) to move the pointer. I think using ptr<T>(y) is a good compromise.

+3
source

at<T> checks the range on each call, making it slower than ptr<T> , but safer.

So, if you are sure that your range calculations are correct and you want the highest possible speed, use ptr<T> .

+2
source

According to official docs, they suggest that the most efficient way is to first get a pointer to a string, and then just use the simple C [] operator. It also saves multiplication for each iteration.

 // compute sum of positive matrix elements // (assuming that M isa double-precision matrix) double sum=0; for(int i = 0; i < M.rows; i++) { const double* Mi = M.ptr<double>(i); for(int j = 0; j < M.cols; j++) sum += std::max(Mi[j], 0.); } 
+1
source

All Articles