Ask Your Question

Loading multiple images from file to the same Mat?

asked 2018-11-07 02:13:23 -0500

Heniek45 gravatar image


Currently if I want to load two images from two different files I have to do this:

cv::Mat image1 = cv::imread("C:\\image1.png"); 
cv::Mat image2 = cv::imread("C:\\image2.png");

Is it possible to reuse the same image1 object and load second image to it when I've finished with first? Function like this would be handy:

cv::Mat image1 = cv::imread("C:\\image1.png"); 
cv::imread(image1, "C:\\image2.png");
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2018-11-07 02:26:43 -0500

berak gravatar image

simply do it like:

cv::Mat image = cv::imread("C:\\image1.png");
// do something with image, then recycle it: 
image = cv::imread("C:\\image2.png");
edit flag offensive delete link more


Thank you. I don't know opencv well, but isn't this causes a new memory allocation and release of old memory?

Heniek45 gravatar imageHeniek45 ( 2018-11-07 02:36:19 -0500 )edit

yes it does, but it's imread() already, where the allocation happens, and you can't avoid it.

and you should not worry too much about allocating memory, nowadays, that's cheap. the number crunching is, where things get interesting...

berak gravatar imageberak ( 2018-11-07 02:51:13 -0500 )edit

The thing is that when I am processing images in realtime from camera 24/7 it adds up. It would be good to avoid this if it is not necessary. Since images always come with the same size it would be nice to have an overload like I've shown and to reuse already allocated buffer. But I guess I will have to live with it, thanks.

Heniek45 gravatar imageHeniek45 ( 2018-11-07 02:57:20 -0500 )edit

why would it add up ? reassigning a Mat means freeing the old memory first.

berak gravatar imageberak ( 2018-11-07 02:59:38 -0500 )edit
Login/Signup to Answer

Question Tools

1 follower


Asked: 2018-11-07 02:13:23 -0500

Seen: 21 times

Last updated: Nov 07