如何在opencv中交换Mat的行? [英] How to swap rows of Mat in opencv?

查看:143
本文介绍了如何在opencv中交换Mat的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Mat M 中交换两行,但我有两个小问题:

I want to swap two rows in a Mat M, and I have two minor problems:

  1. 要交换两行,我需要一个 MatrixRow temp(伪代码)来备份要替换的第一行.但我不知道 Mat 的一行应该是什么类型.
  1. To swap two rows I will need a 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();

这段代码不会改变img,为什么?

This code doesn't change the img, why?

推荐答案

img.row(i) = img.row(j).clone();

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)  

请参阅文档

矩阵分配是一个 O(1) 运算.这意味着没有数据复制但数据是共享的,并且引用计数器(如果有)是递增.

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;

这里,img.row(j) + 0 创建了一个矩阵表达式,所以你调用了 Mat&cv::Mat::operator= (const MatExpr& expr) img.row(i) = img.row(j) + 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;.

另一种选择是按照另一个答案的说明复制数据.您可以为此使用 Mat::copyTo.

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.

这篇关于如何在opencv中交换Mat的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆