# submat roi help

I want to extract a submatrix from a martix at a particular instant and add it to the main matrix while the submatrix remains constant and the main matrix changes ...

I m confused using submat() function and ROI concept...

Pls explain me about submat,ROI,colRange,rowRange and also locateROI

edit retag close merge delete

Sort by ยป oldest newest most voted

Mat object in OpenCV use reference counting approach. Mat has reference to buffer and buffer parameters. When you get submat, you get new Mat that shares image data buffer with original Mat. You need to copy ROI to new Mat with Mat::copyTo method and make all calculations with submat copy.

more

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

more

So will the main matrix be altered after addition?? since we take only reference for the submatrix...right??

( 2013-02-01 22:28:26 -0500 )edit

Yes, it will be altered.

( 2013-02-02 02:53:26 -0500 )edit

thank u so much...again i have an issue.. when the roi starting point is near the bounday and if the height,width exceeds the boundary level,then the prog stops...how can i fix it??

( 2013-02-02 03:35:20 -0500 )edit
1

It does not matter if it is Mat or just a simple array you allocated, accessing to memory outside of array boundaries is always causing crashes. So if this may happen then you must check that rectangle of sub-matrix is completely inside original image. It should be something like: if (roi1 & Rect(0,0,width,height) == roi1) than everything is OK.

( 2013-02-02 05:45:15 -0500 )edit

Thanks a lot mike :)

( 2013-02-03 05:59:44 -0500 )edit

Official site

GitHub

Wiki

Documentation