NeoZoom.lua
NeoZoom.lua

Reputation: 2921

How to swap rows of Mat in opencv?

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

  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();

This code doesn't change the img, why?

Upvotes: 1

Views: 1952

Answers (2)

dhanushka
dhanushka

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

Vallabh Karanjkar
Vallabh Karanjkar

Reputation: 19

Instead of using clone, I would recommend you to use the following steps:

  1. Create a temporary mat of the size of 1 row x n columns, where n is the width of image
  2. Copy the pixel values from ith row to temporary mat with the help of for loop
  3. Copy the pixel values from jth row to ith row using the same for loop technique
  4. Copy the pixel values from temporary mat to jth row

This is a solution based on what I understood from the information provided.

Upvotes: 0

Related Questions