The behaviour of copying cv::Mat
is confusing me.
I understand from the documentation that Mat::copyTo()
is deep copy while the assignment ope
I've been using OpenCV for a while now and the cv::Mat
confused me too, so I did some reading.
cv::Mat
is a header that points to a *data
pointer which holds the actual image data. It also implements reference counting. it holds the number of cv::Mat
headers currently pointing to that *data
pointer. So when you do a regular copy such as:
cv::Mat b;
cv::Mat a = b;
a
will point to b
's data and the reference count for it will be incremented. At the same time, the reference count for the data previously pointed to by b
will be decremented (and the memory will be freed if it is 0 after decrementing).
Question 1: It depends on your program. Please refer to this question for more details: is-cvmat-class-flawed-by-design
Question 2: the function returns by value. That means return image
will copy the Mat and increase the ref count(now ref_count = 2
) and return the new Mat. When the function ends, the image will be destroyed and ref_count will be reduced by one. But the memory will not be freed since the ref_count
is not 0. So the returned cv::Mat
is not pointing to random memory location.
Question 3: A similar thing happens. When you say orgImage2.copyTo(aCopy);
The ref_count for the data pointed to by aCopy
will be decreased. Then new memory is allocated to store the new data that will be copied. So That is why copyCopy1
was not modified when you did this.