Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::vector's push_back create a deep copy of the argument?

I have a list of images stored it several Mat objects and I need to push them into a vector of Mat.

vector<Mat> images; 
Mat image;
for ( i = 0; i < n; i++)
{
   \\ importing the i-th image into a mat image; 
   images.push_back(image);
}

Does this create a deep copy of the image?

Sure

vector<Mat> images;
Mat image (100, 100, CV_8UC(1), Scalar::all(255));
images.push_back(image);
image.release(); 
Mat temp (100,100, CV_8UC(1), Scalar::all(0));
image =  temp;
images.push_back(image);
imshow("black", images[0]);
waitKey(0);
imshow("White",images[1]);
waitKey(0); 

this should show one black and one white image.

Another question

Mat img;
vector<mat> images;
for (i = 1; i < 5, i++)
{
    img.create(h,w,type); // h,w and type are given correctly
    // input an image from somewhere to img correctly.
    images.push_back(img);
    img.release();
}
for (i = 1; i < 5; i++) images[i].release();

This still makes me have memory leaks, what may be the reason behind it?

like image 446
Vahagn Tumanyan Avatar asked Oct 24 '25 02:10

Vahagn Tumanyan


1 Answers

std::vector::push_back uses the object's copy constructor to insert an element into a vector. So if the Mat copy constructor creates a deep copy of the Mat object, you get a deep copy.

like image 84
Timo Geusch Avatar answered Oct 25 '25 16:10

Timo Geusch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!