What's the difference between Mat::clone and Mat::copyTo?

前端 未结 4 1636
忘了有多久
忘了有多久 2020-12-29 18:34

I know \'copyTo\' can handle mask. But when mask is not needed, can I use both equally?

http://docs.opencv.org/modules/core/doc/basic_structures.html#mat-clone

相关标签:
4条回答
  • 2020-12-29 18:54

    Mat::copyTo is for when you already have a destination cv::Mat that (may be or) is already allocated with the right data size. Mat::clone is a convenience for when you know you have to allocate a new cv::Mat.

    0 讨论(0)
  • 2020-12-29 19:04

    Actually, they are NOT the same even without mask.

    The major difference is that when the destination matrix and the source matrix have the same type and size, copyTo will not change the address of the destination matrix, while clone will always allocate a new address for the destination matrix.

    This is important when the destination matrix is copied using copy assignment operator before copyTo or clone. For example,

    Using copyTo:

    Mat mat1 = Mat::ones(1, 5, CV_32F);
    Mat mat2 = mat1;
    Mat mat3 = Mat::zeros(1, 5, CV_32F);
    mat3.copyTo(mat1);
    cout << mat1 << endl;
    cout << mat2 << endl;
    

    Output:

    [0, 0, 0, 0, 0]
    [0, 0, 0, 0, 0]
    

    Using clone:

    Mat mat1 = Mat::ones(1, 5, CV_32F);
    Mat mat2 = mat1;
    Mat mat3 = Mat::zeros(1, 5, CV_32F);
    mat1 = mat3.clone();
    cout << mat1 << endl;
    cout << mat2 << endl;
    

    Output:

    [0, 0, 0, 0, 0]
    [1, 1, 1, 1, 1]
    
    0 讨论(0)
  • 2020-12-29 19:05

    copyTo doesn't allocate new memory in the heap which is faster.

    0 讨论(0)
  • 2020-12-29 19:12

    This is the implementation of Mat::clone() function:

    inline Mat Mat::clone() const
    {
      Mat m;
      copyTo(m);
      return m;
    }
    

    So, as @rotating_image had mentioned, if you don't provide mask for copyTo() function, it's same as clone().

    0 讨论(0)
提交回复
热议问题