Updating a submatrix of Mat in OpenCV

前端 未结 2 1488
旧巷少年郎
旧巷少年郎 2021-02-01 18:02

I am working with OpenCV and C++. I have a matrix X like this

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

and I want to update just a submatrix 4x3 of i

2条回答
  •  庸人自扰
    2021-02-01 18:15

    First, you have to create a matrix that points to the original one:

    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
    

    Keep in mind that any operations that involves direct attribution, with the "=" sign from another matrix will change the roi matrix source from orig to that other matrix.

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

提交回复
热议问题