在OpenCV中更新Mat的子矩阵

时间:2012-07-26 07:03:34

标签: c++ opencv

我正在使用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 个答案:

答案 0 :(得分:30)

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

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);

多数民众赞成。

答案 1 :(得分: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

请记住,涉及直接归因的任何操作,来自另一个矩阵的“=”符号会将roi矩阵源从orig更改为其他矩阵。

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