Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV Mat::operator= - does it support copy on write?

Tags:

c++

opencv

From the OpenCV documentation, it appears that copying a matrix is done using a shallow copy, but when changing one of the copies, a copy is done.

The exact reference is:

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

Mat& Mat::operator = (const MatExpr_Base& expr)

Mat& operator = (const Scalar& s)

Matrix assignment operators

Parameters:

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 .

expr – The assigned matrix expression object. As opposite to the first form of assignment operation, the second form can reuse already allocated matrix if it has the right size and type to fit the matrix expression result. It is automatically handled by the real function that the matrix expressions is expanded to. For example, C=A+B is expanded to cv::add(A, B, C) , and add() will take care of automatic C reallocation.

s – The scalar, assigned to each matrix element. The matrix size or type is not changed.

However, this appears not to work

Mat_<float> a(5,5),b(5,5);
a =1;
b = a;
a = 2;

now b == 2, intead of 1

like image 916
Ophir Yoktan Avatar asked Jun 20 '11 12:06

Ophir Yoktan


2 Answers

It seems you misunderstood. "Before assigning new data, the old data is dereferenced via Mat::release" does not mean that when you write on a or b then a copy occurs. It means that when you type b=a, you lose the data that was in b.

Long story short : copy on write is not supported.

like image 70
B. Decoster Avatar answered Oct 17 '22 10:10

B. Decoster


You can make a deep copy with Mat::copyTo(). E.g.

Mat a(5,5,CV_32C1),b;
a = 1;
a.copyTo(b);
a = 2;

But no, Mat does not support copy-on-write. When you need to make a change to a without affecting b, you need to make a deep copy of a to b, and then modify a.

like image 5
Jacob Avatar answered Oct 17 '22 10:10

Jacob