Copy a matrix to a subset of another matrix
I'm having difficulty copying a subset of a matrix into another larger matrix using OpenCV in C++.
I tried the following code:
#include <opencv2/opencv.hpp>
void printMatrix(const cv::Mat &M, std::string matrix)
{
printf("Matrix \"%s\" is %i x %i\n", matrix.c_str(), M.rows, M.cols);
std::cout << M << std::endl;
}
int main(int argc, char ** argv)
{
cv::Mat P0(3, 4, CV_32F);
printMatrix(P0, "P0 Initial");
cv::Mat R0 = cv::Mat::eye(3,3,CV_32F);
printMatrix(R0, "R0 I");
R0.copyTo(P0.colRange(0,2));
printMatrix(P0, "P0 with R");
return 0;
}
Which produces the following output:
Matrix "P0 Initial" is 3 x 4
[-4.3160208e+008, -4.3160208e+开发者_StackOverflow008, -4.3160208e+008, -4.3160208e+008;
-4.3160208e+008, -4.3160208e+008, -4.3160208e+008, -4.3160208e+008;
-4.3160208e+008, -4.3160208e+008, -4.3160208e+008, -4.3160208e+008]
Matrix "R0 I" is 3 x 3
[1, 0, 0;
0, 1, 0;
0, 0, 1]
Matrix "P0 with R" is 3 x 4
[-4.3160208e+008, -4.3160208e+008, -4.3160208e+008, -4.3160208e+008;
-4.3160208e+008, -4.3160208e+008, -4.3160208e+008, -4.3160208e+008;
-4.3160208e+008, -4.3160208e+008, -4.3160208e+008, -4.3160208e+008]
While suggests that the copy operation is not doing anything.
I found a similar post here but updating the relevant line to the following as suggested in that post still produces the same output.
//R0.copyTo(P0.colRange(0,2));
cv::Mat dest = P0.colRange(0,2);
printMatrix(P0, "P0 with R");
Your code doesn't compile for me. I get an error at R0.copyTo(P0.colRange(0,2));
(and also if I try R0.copyTo(P0.colRange(0,3));
which has the correct range.) But this does work for me:
cv::Mat dest(P0.colRange(0,3));
R0.copyTo(dest);
printMatrix(P0, "P0 with R");
You almost had it in your last code example, but you left out copyTo
(and your range was incorrect).
精彩评论