Dead-coder
Dead-coder

Reputation: 340

OpenCV = operator

I am working on OpenCV and I have a confusion. I went through this link and I did not quite understand the concept of '=' operator in OpenCV.

Suppose I declare 3 Matrices as follows:

Mat img1, img2, gray;

If I obtain the matrix gray from the image captured from the camera and assign it to img1 as mentioned below, what actually happens? Does the data in gray get copied to img1 or is it that data is shared between them?

img1 = gray;

Upvotes: 3

Views: 1616

Answers (2)

1''
1''

Reputation: 27095

OpenCV's Mat class is simply a header for the actual image data, which it contains a pointer to. The = operator copies the pointer (and the other information in the header, like the image dimensions) so that both Mats share the same data. This means that modifying the data in one Mat also changes it in the other. This is called a "shallow" copy, since only the top layer (the header) is copied, not the lower layer (the data).

To make a copy of the underlying data (called a "deep copy"), use the clone() method. You can find information about it on the page that you linked to.

Upvotes: 8

Mahesh
Mahesh

Reputation: 34625

It explains in the link you provided.

Mat& Mat::operator = (const Mat& m)

m :The assigned, right-hand-side matrix. Matrix assignment is O(1) operation, that is, no data is copied. Instead, the data is shared and the reference counter, if any, is incremented. Before assigning new data, the old data is dereferenced via Mat::release .

Upvotes: 1

Related Questions