0

Consider two matrices as input parameters of the following sample_method() method, I want to merge the two matrices m1 and m2 in a new matrix m12. I read this reference and then also this reference, but these two solutions copy the data from source matrices to the destination matrix.

bool sample_method(const Mat& m1, const Mat& m2)
{
    if(m1.cols != m2.cols)
    {
        cout << "Error: m1.cols != m2.cols" << endl;
        return false;
    }

    Mat m12(m1.rows+m2.rows,m1.cols,DataType<float>::type);
    // merging m1 and m2
    m12(Rect(0,0,m1.cols,m1.rows)) = m1;
    m12(Rect(0,m1.rows,m2.cols,m2.rows)) = m2;

    return true;
}

How could I concatenate two Mat in a single Mat without copying the data? Why my code does not work?

Community
  • 1
  • 1
enzom83
  • 8,080
  • 10
  • 68
  • 114

2 Answers2

4

I don't think you are ever going to get that to work. A Mat object has one pointer to its data and then parameters that help it to interpret that data. You are asking to make a Mat out of two unrelated blocks of memory, there is no way to do that without somehow storing a pointer to both of them and Mat does not have a member variable to put it in..

Hammer
  • 10,109
  • 1
  • 36
  • 52
1
m12(Rect(0,0,m1.cols,m1.rows)) = m1;

the left part creates a header for the specified part of m12 matrix. When you assign m1 to to this header - this header begins point to the same data as a m1. Note: no copying the data there. This code do nothing

It's no possible to merge two matrices without copying the data.

sandye51
  • 91
  • 9