开发者

In OpenCV 2.1: How to assign a matrix to a submatrix of another matrix?

开发者 https://www.devze.com 2023-01-22 08:07 出处:网络
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.

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?


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

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


Revised answer

I believe the reason your first method

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

doesn't work is because the assignment operator = does not copy values but modifies the header of a matrix to point at a submatrix of another. Therefore all this line does is create a temporary header matrix pointing to the submatrix of A, and then replace the header of that temporary matrix to point at B. And then forget about it. The data in A and B remains unchanged.

What you want (although I've not tested it) is

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


You can do this in one line with:

B = A(cv::Rect(0,0,2,2)).clone();


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

0

精彩评论

暂无评论...
验证码 换一张
取 消