首页 文章

在OpenCV中更新Mat的子矩阵

提问于
浏览
24

我正在使用OpenCV和C . 我有一个像这样的矩阵X.

Mat X = Mat::zeros(13,6,CV_32FC1);

我想更新它的子矩阵4x3,但我怀疑如何以有效的方式访问该矩阵 .

Mat mat43= Mat::eye(4,3,CV_32FC1);  //this is a submatrix at position (4,4)

我是否需要逐个元素地更改?

2 回答

  • 29

    最快捷的方法之一是设置一个 Headers 矩阵,指向要更新的列/行范围,如下所示:

    Mat aux = X.colRange(4,7).rowRange(4,8); // you are pointing to submatrix 4x3 at X(4,4)
    

    现在,您可以将矩阵复制到aux(但实际上您将其复制到X,因为aux只是一个指针):

    mat43.copyTo(aux);
    

    而已 .

  • 13

    首先,您必须创建一个指向原始矩阵的矩阵:

    Mat orig(13,6,CV_32FC1, Scalar::all(0));
    
    Mat roi(orig(cv::Rect(1,1,4,3))); // now, it points to the original matrix;
    
    Mat otherMatrix = Mat::eye(4,3,CV_32FC1);
    
    roi.setTo(5);                // OK
    roi = 4.7f;                  // OK
    otherMatrix.copyTo(roi);     // OK
    

    请记住,涉及直接归属的 any 操作与来自另一个矩阵的"="符号会将roi矩阵源从orig更改为其他矩阵 .

    // Wrong. Roi will point to otherMatrix, and orig remains unchanged
    roi = otherMatrix;
    

相关问题