fececagec812
fececagec812

Reputation: 394

if M is a cv::Mat, why will M.col(1) = M.col(7) not work?

If M is a cv::Mat , the following codes will work:

Mat M1 = M.col(1);

M.col(7).copyTo(M1);

But this will not:

M.col(1) = M.col(7)

why?

Update:
I found the explanation provided by official doc:
cv::Mat::row()

Upvotes: 2

Views: 142

Answers (2)

Markus Dutschke
Markus Dutschke

Reputation: 10606

As your link to the docs of cv::Mat::row is broken, here the excerpt:

In the current implementation, the following code does not work as expected:

Mat A; ... A.row(i) = A.row(j); // will not work

This happens because A.row(i) forms a temporary header that is further assigned to another header. Remember that each of these operations is O(1), that is, no data is copied. Thus, the above assignment is not true if you may have expected the j-th row to be copied to the i-th row. To achieve that, you should either turn this simple assignment into an expression or use the Mat::copyTo method:

Mat A;
...
// works, but looks a bit obscure.
A.row(i) = A.row(j) + 0;
// this is a bit longer, but the recommended method.
A.row(j).copyTo(A.row(i));

Summary

So long story short: A.row(i) and A.row(j) are headers. You can not assign a header to a header. A.row(j) + 0 is an expression however. When you assign an expression to a header, the data is copied, where it belongs to.

Upvotes: 0

Michael Burdinov
Michael Burdinov

Reputation: 4448

You should use:

M.col(7).copyTo(M.col(1));

copyTo function copy the data from one matrix to another (i.e. perform deep copy). Operator "equal", on the other hand, only copy one pointer to another (i.e. perform shallow copy).

And M.col() is a constant point that can't be reassigned anyway.

Upvotes: 2

Related Questions