Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Strange behavior of * and + on cv::Mat

Hi

I'm new in opencv, but I found some strange behavior when I was using * and + on cv::Mat. I have build opencv 4.2.0 myself and I'm using that version.

1- different between * and *=

Look at following code:

auto mat = cv::Mat::eye(2, 2, CV_32FC3);
std::cout << mat << "\n\n";
mat = mat * 0.5;
std::cout << mat << "\n";

This code has the following result:

[1, 0, 0, 0, 0, 0;
0, 0, 0, 1, 0, 0]

[0.5, 0, 0, 0, 0, 0;
0, 0, 0, 0.5, 0, 0]

but this code:

auto mat = cv::Mat::eye(2, 2, CV_32FC3);
std::cout << mat << "\n\n";
mat *= 0.5;
std::cout << mat << "\n";

This code has the following result:

[1, 0, 0, 0, 0, 0;
0, 0, 0, 1, 0, 0]

[1, 0, 0, 0, 0, 0;
0, 0, 0, 1, 0, 0]

means it has no effect on matrix. Any idea why? In addition why when I create a 3 channel (CV_32FC3) matrix with cv::Mat::eye, only first channel has values of 1 rather than all 3 channels?

2- why + only affect first channel?

Look at following code:

auto mat = cv::Mat::eye(2, 2, CV_32FC3);
std::cout << mat << "\n\n";
mat = mat + 0.5;
std::cout << mat << "\n";

This code has the following result:

[1, 0, 0, 0, 0, 0;
0, 0, 0, 1, 0, 0]

[1.5, 0, 0, 0.5, 0, 0;
0.5, 0, 0, 1.5, 0, 0]

why + only affect first channel rather than all channels? This happens while * affect all 3 channels. In addition, similar to *= case, += does not work too.