user1726
user1726

Reputation: 65

copyTo() vs clone() inside function?

I've just begun learning C++ and OpenCV. I'm trying to make my own function but I'm confused as to why copyTo(dst); works, but when I use dst = src.clone(); the displayed output is black?

void testFunc(InputArray _src, OutputArray _dst){
    Mat src = _src.getMat();
    _dst.create(src.size(), src.type());
    Mat dst = _dst.getMat();
    src.copyTo(dst);
    // ^this works but
    // dst = src.clone(); doesn't
}

Upvotes: 2

Views: 1695

Answers (1)

ilent2
ilent2

Reputation: 5241

I think one way to resolve this issue is to treat Mat as a pointer (not quite correct, but humour me for a moment).

In your example you create Mat src which points to the source matrix. You then create a matrix for the destination with create(...) and create a new pointer Mat dst to this new matrix. When you use src.copyTo(dst), OpenCV copies the data pointed to by src into the target pointed to by dst, however when you use the assignment dst = src.clone(), dst is replaced with a clone of src (that is, the pointer is changed to a new location).

With basic types, this could translate to something like:

struct Input { int* data; };
struct Output { int* data; };

void testFunc(Input _src, Output _dst)
{
    int* src = _src.data;
    _dst.data = new int;
    int* dst = _dst.data;

    // src.copyTo(dst)
    *dst = *src;

    // dst = src.clone()
    dst = new int(*src);
}

This way of thinking about it is not entirely correct, but it might be useful for thinking about this behaviour.

Upvotes: 5

Related Questions