为什么矩阵没有正确初始化/打印?

时间:2016-10-12 15:44:09

标签: c++ opencv matrix printing initialization

我正在使用cv :: Mat并认为我的代码确实很奇怪,尽管我遵循here中描述的语法。

代码:

std::cout << "parameter for matrices: " << "x = " << X << " y = " << Y << " psi = " << Psi << std::endl;
double dataRot[] = { cos(Psi), -sin(Psi), sin(Psi), cos(Psi) };
double dataTrans[] = { X, Y };
cv::Mat matRot(2, 2, CV_32FC1, dataRot);
cv::Mat matTrans(2, 1, CV_32FC1, dataTrans);
std::cout << "matRot = " << matRot.at<double>(0,0) << "," << matRot.at<double>(0,1) << ";" << matRot.at<double>(1,0) << "," << matRot.at<double>(1,1) << std::endl;
std::cout << "matRot = " << matRot << std::endl;
std::cout << "matTrans = " << matTrans.at<double>(0,0) << "," << matTrans.at<double>(0,1) << std::endl;
std::cout << "matTrans = " << matTrans << std::endl;
matOut = matRot*matIn + matTrans*cv::Mat::ones(1, matIn.cols, CV_32FC1);

输出:

parameter for matrices: x = 20.5 y = 20 psi = 0
matRot = 1,-0;-0,0
matRot = [0, 1.875;
  0, -0]
matTrans = 20.5,20
matTrans = [0; 2.8203125]

为什么单位矩阵未正确初始化? 为什么打印矩阵的第二种方式会产生错误的结果呢? 任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

由于您正在使用double,因此OpenCV矩阵类型应为CV_64FC1

cv::Mat matRot(2, 2, CV_64FC1, dataRot);
cv::Mat matTrans(2, 1, CV_64FC1, dataTrans);

为简单起见,您还可以使用:

cv::Matx22d matRot(cos(Psi), -sin(Psi), sin(Psi), cos(Psi));
cv::Matx21d matTrans(X, Y);

或:

cv::Mat1d matRot = (cv::Mat1d(2,2) << cos(Psi), -sin(Psi), sin(Psi), cos(Psi));
cv::Mat1d matTrans = (cv::Mat1d(2,1) << X, Y);

并访问以下值:

std::cout << matRot(row, col);