Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV submatrix access: copy or reference?

If I extract a submatrix from a matrix using

cv::Mat A = cv::Mat::ones(4,4);

cv::Mat B = A( cv::Rect( 1, 1, 2, 2 ) );

Is "B" a copy of those values from "A" or does it reference to those values?

Could you provide an example of how to get

(1) a copy of the submatrix?

(2) a reference to the submatrix?

like image 544
S.H Avatar asked Jan 08 '15 07:01

S.H


People also ask

What is use of mat class in OpenCV?

The Mat class of OpenCV library is used to store the values of an image. It represents an n-dimensional array and is used to store image data of grayscale or color images, voxel volumes, vector fields, point clouds, tensors, histograms, etc.

What is CV_8U?

CV_8U is unsigned 8bit/pixel - ie a pixel can have values 0-255, this is the normal range for most image and video formats.

What is CV_64F?

CV_64F is the same as CV_64FC1 . So if you need just 2D matrix (i.e. single channeled) you can just use CV_64F. EDIT. More generally, type name of a Mat object consists of several parts.

What is scalar OpenCV?

ScalarRepresents a 4-element vector. The type Scalar is widely used in OpenCV for passing pixel values. In this tutorial, we will use it extensively to represent BGR color values (3 parameters). It is not necessary to define the last argument if it is not going to be used.


1 Answers

B is a copy of A's Mat-header, but references the same pixels.

so, if you manipulate B's pixels, A is affected, too.

(1) (a 'deep copy') would be:

cv::Rect r( 1, 1, 2, 2 );
cv::Mat A = cv::Mat::ones(4,4);
cv::Mat B = A(r).clone(); // now B has a seperate *copy* of the pixels

cv::Mat C; 
A(r).copyTo(C);           // another way to make a 'deep copy'

(2) (a 'shallow copy'), that's what you're doing above already:

cv::Mat B = A(r);         // B points to A's pixels
like image 157
berak Avatar answered Sep 19 '22 05:09

berak