2016-08-18 85 views
1

documentation定义了一个cv::Mat括号操作员在cv::Rect类型感兴趣的矩形区域作为一个参数:cv :: Mat括号运算符是否复制或引用感兴趣的区域?

Mat cv::Mat::operator() (const Rect & roi) const

但文档不解释操作的语义。它是否复制感兴趣的区域?或者它是否在创建的新Mat中引用它?

如果我改变原来的垫,新的也会改变吗?

我的猜测是它复制,因为在大多数情况下,roi不是连续的内存块。但文档没有明确说明,所以我只是想确保它不会牵扯到最终耦合两个Mats的特殊内存技巧。

回答

2

这是一个参考,除非您明确复制数据。


为此,可以使用一个小例子看看:

#include <opencv2/opencv.hpp> 
#include <iostream> 
using namespace cv; 
using namespace std; 

int main() 
{ 
    Rect r(0,0,2,2); 
    Mat1b mat(3,3, uchar(0)); 
    cout << mat << endl; 

    // mat 
    // 0 0 0 
    // 0 0 0 
    // 0 0 0 

    Mat1b submat_reference1(mat(r)); 
    submat_reference1(0,0) = 1; 
    cout << mat << endl; 
    cout << submat_reference1 << endl; 

    // mat 
    // 1 0 0 
    // 0 0 0 
    // 0 0 0 

    // submat_reference1 
    // 1 0 
    // 0 0 

    Mat1b submat_reference2 = mat(r); 
    submat_reference2(0, 0) = 2; 
    cout << mat << endl; 
    cout << submat_reference1 << endl; 
    cout << submat_reference2<< endl; 
    // mat 
    // 2 0 0 
    // 0 0 0 
    // 0 0 0 

    // submat_reference1 = submat_reference2 
    // 2 0 
    // 0 0 


    Mat1b submat_deepcopy = mat(r).clone(); 
    submat_deepcopy(0,0) = 3; 
    cout << mat << endl; 
    cout << submat_reference1 << endl; 
    cout << submat_reference2 << endl; 
    cout << submat_deepcopy << endl; 

    // mat  
    // 2 0 0 
    // 0 0 0 
    // 0 0 0 

    // submat_reference1 = submat_reference2 
    // 2 0 
    // 0 0 

    // submat_deepcopy 
    // 3 0 
    // 0 0 

    return 0; 
} 
相关问题