Ask Your Question

how is b=a.clone() different than a.copyTo(b)? which is faster?

asked 2017-01-16 00:36:01 -0500

jp2112 gravatar image

For an image processing demo I need to squeeze every bit of optimization out of my code to get a higher frame rate, but I'm familiar with hardware programming (VHDL) and not so much with CPU programming languages. So it's not clear to me how much faster code can run by moving statements such as variable declarations outside of loops and functions, i.e., does encountering a type declaration millions of times actually slow down execution? To this end, there also seem to be different methods to performing the same OpenCV array tasks on Mat types. My big question at this time is whether I should use clone or copyTo if I simply want to make a copy of an existing Mat array. Does it matter if the dst array has already been declared with the same size as the src? Thanks.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2017-01-16 01:47:21 -0500

LBerger gravatar image

Do like you want :

clone source is

Mat Mat::clone() const
    Mat m;
    return m;

if you want to test :

TickMeter chronometer;
Mat a(500,500,CV_8UC1);
RNG rr;

rr.fill(a,CV_8UC1, RNG::UNIFORM, 0, 256);

for (int i = 0; i < 1000; i++)
    Mat b = a.clone();

cout << "Clone " << chronometer.getTimeSec() << endl;
for (int i = 0; i < 1000; i++)
    Mat b;

cout << "Copy " << chronometer.getTimeSec() << endl;
edit flag offensive delete link more


Thanks for this code to run. It gives me practically identical results for clone and copyTo. So am I correct to understand that clone is actually just a copyTo operation nested within a function call? Why would this be necessary? Anyhow, I have my answer in that I will just use copyTo.

jp2112 gravatar imagejp2112 ( 2017-01-16 17:02:17 -0500 )edit

Question Tools

1 follower


Asked: 2017-01-16 00:36:01 -0500

Seen: 2,173 times

Last updated: Jan 16 '17