Deep Copy of OpenCV cv::Mat

前端 未结 3 1288
春和景丽
春和景丽 2021-02-01 03:48

The behaviour of copying cv::Mat is confusing me.

I understand from the documentation that Mat::copyTo() is deep copy while the assignment ope

3条回答
  •  醉梦人生
    2021-02-01 04:27

    I think, that using assignment is not the best way of matrix copying. If you want new full copy of the matrix, use:

    Mat a=b.clone(); 
    

    If you want copy matrix for replace the data from another matrix (for avoid memory reallocation) use:

    Mat a(b.size(),b.type());
    b.copyTo(a);
    

    When you assign one matrix to another, the counter of references of smart pointer to matrix data increased by one, when you release matrix (it can be done implicitly when leave code block) it decreases by one. When it becomes equal zero the allocated memory deallocated.

    If you want get result from the function use references it is faster:

    void Func(Mat& input,Mat& output)
    {
     somefunc(input,output);
    }
    
    int main(void)
    {
    ...
      Mat a=Mat(.....);
      Mat b=Mat(.....);
      Func(a,b);
    ...
    }
    

提交回复
热议问题