# Apply function to each Mat element

Does anyone know of a more efficient OpenCV practice to perform the following operation on each Mat element ? Each element undergoes the same function.

Mat calcDepthValues(Mat &depth){

Mat realDepth= depth.clone();

Mat_<double>::iterator it = realDepth.begin<double>();
Mat_<double>::iterator itend = realDepth.end<double>();

for (; it != itend; ++it) {

(*it) = 448.251214 +  ((1- (*it)/255)  * 10758.02914);

}
return realDepthValues;

edit retag close merge delete

1

So you suggest first dividing all elements by 255, then negating it, then adding 1, then using the mul() function , and so on ... for each step of the algorithm ?

Wow, that's the fastest "deep look" I've ever seen in 3 minutes time... I'm suggesting you to understand how to take advantage of OpenCV's overloaded functions that operate on complete matrices, instead of coding poor per-pixel loops on your own.

... cause I've been looking "deeply" at it for quite some time today, but I'm still getting used to how OpenCV operates. I think i understand what you mean.

Sort by » oldest newest most voted

Agree with @LorenaGdL about using basic matrix operations which are optimized by SSE, AVX codes and other parallel techniques (if needed). Your code should be:

void calcDepthValues(const Mat &depth, Mat & realDepth){ // should not return a Mat, it can be a very huge object
realDepth= depth.clone();
float a = -10758.02914f/255; // fix it if you already knew it
float b = 448.251214f+10758.02914f; // fix it if you already knew it

realDepth *= a;
realDepth += b;
}

more

Official site

GitHub

Wiki

Documentation