SomethingSomething
SomethingSomething

Reputation: 12276

OpenCV: mathematical operations on matrices like in Matlab

I have a pretty basic question.

The below Matlab code takes 2 matrices with same dimensions (matrix1, matrix2), and produces a new matrix, result_matrix, which in each index (i,j), it contains sqrt(matrix1[i][j] ^ 2 + matrix2[i][j] ^ 2).

How would you convert this simple Matlab code into OpenCV in C++, such that it would be most simple, clear and efficient?

result_matrix = sqrt(matrix1 .^ 2 + matrix2 .^ 2);

Upvotes: 1

Views: 78

Answers (2)

Miki
Miki

Reputation: 41775

For this specific operation:

result_matrix = sqrt(matrix1 .^ 2 + matrix2 .^ 2);

you can use magnitude:

Mat m1 = ...
Mat m2 = ...
Mat m3;
magnitude(m1, m2, m3);

This is 3-4 times faster than @mirosval code.

Upvotes: 3

mirosval
mirosval

Reputation: 6832

Assuming you have the matrices a, b, c

Mat a;
Mat b;
Mat c;

you can do this:

pow(a, 2, a);
pow(b, 2, b);
sqrt(a + b, c);

At the end c will contain the result. See docs for pow() and sqrt() the sum is done via the + operator on Mat, see here

Upvotes: 1

Related Questions