opencv

What is the purpose of cv::MatExpr?


OpenCV arithmetic operations produce a cv::MatExpr, for example:

MatExproperator+(const Mat & a, const Mat &b);

I see that this is used to represent an expression before it is evaluated. What is the purpose of doing this?


Solution

  • Let's say you have this expression:

    Mat A = 3 + B * 5;
    

    where B is also a Mat.

    If the operators + and * were to return a Mat, B * 5 would have created a temporary Mat and then the + operator would have created another Mat. Instead, B * 5 returns a MatExpr that doesn't actually create a Mat, it just "remembers" the operation it needs to perform. Then, the + operator creates another MatExpr and only the = operator creates a Mat, thus avoiding the temporary Mat.

    See https://en.wikipedia.org/wiki/Lazy_evaluation.