Reputation: 2921
I want to swap two rows in a Mat M
, and I have two minor problems:
MatrixRow temp
(pseudo code) to backup the first row to be replaced. But I don't know what should be the type of a row of a Mat
.Mat temp = img.row(i).clone();
img.row(i) = img.row(j).clone();
img.row(j) = temp.clone();
This code doesn't change the img, why?
Upvotes: 1
Views: 1952
Reputation: 10702
img.row(i) = img.row(j).clone();
and
img.row(j) = temp.clone();
do not copy the cloned data because they invoke the following assignment operator
Mat& cv::Mat::operator= (const Mat& m)
See the documentation
Matrix assignment is an O(1) operation. This means that no data is copied but the data is shared and the reference counter, if any, is incremented.
To do the copying, there's another assignment operator that you can use:
Mat& cv::Mat::operator= (const MatExpr& expr)
See matrix expressions for details.
So, you can do something like the following to actually copy the data.
img.row(i) = img.row(j).clone() + 0;
img.row(j) = temp.clone() + 0;
And, you don't need clone. So it can be written as
img.row(i) = img.row(j) + 0;
img.row(j) = temp + 0;
Here, img.row(j) + 0
creates a matrix expression, so you invoke the Mat& cv::Mat::operator= (const MatExpr& expr)
assignment operator in img.row(i) = img.row(j) + 0;
.
And the other option is to copy the data as the other answer says. You can use Mat::copyTo
for this.
For further details, see the note in the documentation for
Mat cv::Mat::row(int y) const
It explains this with examples.
Upvotes: 3
Reputation: 19
Instead of using clone, I would recommend you to use the following steps:
This is a solution based on what I understood from the information provided.
Upvotes: 0