cv::Mat 括号运算符是否复制或引用感兴趣的区域?

Does the cv::Mat parentheses operator copy or reference an area of interest?

这个 documentationcv::Mat 上定义了一个括号运算符,它接受类型为 cv::Rect 的感兴趣的矩形区域作为参数:

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

但是文档没有解释运算符的语义。它是否复制感兴趣的区域?或者它是否在创建的新 Mat 中引用它?

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

我的猜测是它复制了,因为在大多数情况下 roi 不是连续的内存块。但是文档没有明确说明这一点,所以我只是想确保它没有拉出一些特殊的记忆技巧,最终耦合两个垫子。

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


您可以使用一个小示例来了解这一点:

#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;
}