C++ 在 OpenCV 中更新 Mat 的子矩阵
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11664097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Updating a submatrix of Mat in OpenCV
提问by Carlos Cachalote
I am working with OpenCV and C++. I have a matrix X like this
我正在使用 OpenCV 和 C++。我有一个这样的矩阵 X
Mat X = Mat::zeros(13,6,CV_32FC1);
and I want to update just a submatrix 4x3 of it, but I have doubts on how to access that matrix in an efficient way.
我只想更新它的一个 4x3 子矩阵,但我怀疑如何以有效的方式访问该矩阵。
Mat mat43= Mat::eye(4,3,CV_32FC1); //this is a submatrix at position (4,4)
Do I need to change element by element?
我需要逐个元素更改吗?
回答by Jav_Rock
One of the quickest ways is setting a header matrix pointing to the range of columns/rows you want to update, like this:
最快的方法之一是设置指向要更新的列/行范围的标题矩阵,如下所示:
Mat aux = X.colRange(4,7).rowRange(4,8); // you are pointing to submatrix 4x3 at X(4,4)
Now, you can copy your matrix to aux (but actually you will be copying it to X, because aux is just a pointer):
现在,您可以将矩阵复制到 aux(但实际上您将其复制到 X,因为 aux 只是一个指针):
mat43.copyTo(aux);
Thats it.
就是这样。
回答by Sam
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 anyoperations that involves direct attribution, with the "=" sign from another matrix will change the roi matrix source from orig to that other matrix.
请记住,任何涉及直接归因的操作,带有来自另一个矩阵的“=”符号都会将 roi 矩阵源从 orig 更改为另一个矩阵。
// Wrong. Roi will point to otherMatrix, and orig remains unchanged
roi = otherMatrix;