tags:

views:

42

answers:

2

Assume I have a matrix A = cv::Mat(3,3,CV_32F) and a matrix B = cv::Mat(2,2,CV_32F). Let's say A has all zeros and B has all ones. I want to assign the values of B to the upper left corner of A. How can I do this?

I tried the following:

A(cv::Rect_<int>(0,0,2,2)) = B

But this doesn't seem to work. However assigning a scalar value to the subrect of A this way does work:

A(cv::Rect_<int>(0,0,2,2)) = 1.0

What is wrong with the first approach?

A: 

Don't be afraid to work with pointers

const unsigned int row_size = col_size = 3;    
Mat A = Mat::one( row_size, col_size, CV_32F );
Mat B = Mat::zeros( row_size, col_size, CV_32F );

for(int i = 0; i < row_size; i++)
{
    float* Aitt = A.ptr<float>(i);
    float* Bitt = B.ptr<float>(i);

    for(int j = 0; j < ( col_size - i ); ++j)
        Aitt[j] = Bitt[j];
}

What is wrong with the first approach?

To many Matlab time

Guillaume Massé
I'd like a little more compact version ;)
Christian
+1  A: 

I'd prefer a one-liner, but this does the trick:

cv::Mat tmp = A(cv::Rect(0,0,2,2));
B.copyTo(A);
Christian