25

I am working with OpenCV and C++. I have a matrix X like this

Mat X = Mat::zeros(13,6,CV_32FC1);

and I want to update just a submatrix 4x3 of it, but I have doubts on how to access that matrix in an efficient way.

Mat mat43= Mat::eye(4,3,CV_32FC1);  //this is a submatrix at position (4,4)

Do I need to change element by element?

2 Answers 2

36

One of the quickest ways is setting a header matrix pointing to the range of columns/rows you want to update, like this:

Mat aux = X.colRange(4,7).rowRange(4,8); // you are pointing to submatrix 4x3 at X(4,4)

Now, you can copy your matrix to aux (but actually you will be copying it to X, because aux is just a pointer):

mat43.copyTo(aux);

Thats it.

1
  • 2
    I think OpenCV should add a parameter to control whether the reallocation of Mat::copyTo is allowed. If I unluckily make the size of aux different from aux, the meaning of the code will be changed totally. Sep 23, 2014 at 3:53
13

First, you have to create a matrix that points to the original one:

Mat orig(13,6,CV_32FC1, Scalar::all(0));

Mat roi(orig(cv::Rect(1,1,4,3))); // now, it points to the original matrix;

Mat otherMatrix = Mat::eye(4,3,CV_32FC1);

roi.setTo(5);                // OK
roi = 4.7f;                  // OK
otherMatrix.copyTo(roi);     // OK

Keep in mind that any operations that involves direct attribution, with the "=" sign from another matrix will change the roi matrix source from orig to that other matrix.

// Wrong. Roi will point to otherMatrix, and orig remains unchanged
roi = otherMatrix;            

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.