# Revision history [back]

First of all you can't add sub matrix to whole matrix because their size is different. You can only add it to another sub matrix of the same size.

// define location of sub matrices in image
Rect roi1( x1, y1, sub_width, sub_height );
Rect roi2( x2, y2, sub_width, sub_height );

// define sub matrices in main matrix
Mat sub1( main_mat, roi1 );
Mat sub2( main_mat, roi2 );


Note that no copy was performed. sub1 and sub2 both uses buffer of original image so any change in them will change original image.

// if there no intersection between roi1 and roi2 you simply do the following
sub2 += sub1;


But if there intersection between them this may lead to undefined results because sub1 will change during the addition. So you will need first to copy it to another place first, and only then perform addition.

// if roi1 and roi2 do intersect
sub2 += sub1.clone();


By the way, intersection of rectangles can be checked in following way:

if ( (roi1 & roi2).width == 0 )
// no intersection