我想在Mat M
中交换两行,但有两个小问题:
MatrixRow temp
(伪代码)来备份要替换的第一行。但是我不知道Mat
的行的类型应该是什么。 Mat temp = img.row(i).clone();
img.row(i) = img.row(j).clone();
img.row(j) = temp.clone();
这段代码不会更改img,为什么呢?
最佳答案
img.row(i) = img.row(j).clone();
和img.row(j) = temp.clone();
不要复制克隆的数据,因为它们会调用以下赋值运算符Mat& cv::Mat::operator= (const Mat& m)
见documentationMatrix 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.
要进行复制,可以使用another assignment operator:
Mat& cv::Mat::operator= (const MatExpr& expr)
有关详细信息,请参见matrix expressions。因此,您可以执行以下操作来实际复制数据。
img.row(i) = img.row(j).clone() + 0;
img.row(j) = temp.clone() + 0;
而且,您不需要克隆。所以可以写成img.row(i) = img.row(j) + 0;
img.row(j) = temp + 0;
在这里,img.row(j) + 0
创建一个矩阵表达式,因此您可以在Mat& cv::Mat::operator= (const MatExpr& expr)
中调用img.row(i) = img.row(j) + 0;
赋值运算符。另一个选择是像另一个答案所说的那样复制数据。您可以为此使用
Mat::copyTo
。有关更多详细信息,请参见documentation中的注释
Mat cv::Mat::row(int y) const
它通过示例解释了这一点。
关于c++ - 如何在opencv中交换Mat的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63930667/