qq_40229456 2021-07-17 10:19 采纳率: 100%

# opencv 为啥这个变量的值在函数里面是对的，传出来就出错了呢

``````
#include <iostream>
#include<opencv2\opencv.hpp>
#include<vector>
using namespace std;
using namespace cv;
#define PI 3.1415926535

double TWOPI = 2.0 * PI;
if (t >= 0)
{
t = fmod(t + PI, TWOPI) - PI;
}
else
{
t = fmod(t - PI, -TWOPI) + PI;
}
cout << "standardRad(t):" << t << endl;
return t;
}
Mat wRo_to_euler(Mat wRo) {
cout << "wRo: " << wRo << endl;
double yaw = standardRad(atan2(wRo.at<double>(1, 0), wRo.at<double>(0, 0)));
double c = cos(yaw);
double s = sin(yaw);
wRo.at<double>(0, 0)*c + wRo.at<double>(1, 0)*s)) / PI * 180;

double roll = standardRad(atan2(wRo.at<double>(0, 2) * s - wRo.at<double>(1, 2)*c,
-wRo.at<double>(0, 1)*s + wRo.at<double>(1, 1)*c)) / PI * 180;
cout << "pitch: " << pitch << endl;
cout << "roll: " << roll << endl;
double returnWro_arr[3];
returnWro_arr[0] = roll;
returnWro_arr[1] = pitch;
returnWro_arr[2] = yaw / PI * 180;
Mat returnWro = Mat(1, 3, CV_64F, returnWro_arr);

cout << "returnWro: " << returnWro << endl;
/*cout << "returnWro.rows: "<<returnWro.rows << endl;
cout << "returnWro.cols: "<<returnWro.cols << endl;*/

return returnWro;    //returnWro的x,y,z坐标
}
int main()
{
/*double h_arr[3][3] = { -0.01806375821938705, 0.9813313999097074, -0.1915334800712387,
-0.9997671236683783, -0.01481447609281841, 0.01505010620015893,
-0.01806375821938705, 0.1917530047987496, 0.9813706844588156 };
Mat h = Mat(3, 3, CV_64F, h_arr);*/
Mat h = (Mat_<double>(3, 3) << -0.01806375821938705, 0.9813313999097074, -0.1915334800712387,
-0.9997671236683783, -0.01481447609281841, 0.01505010620015893,
-0.01806375821938705, 0.1917530047987496, 0.9813706844588156);
cout << "h: " << h << endl;
//Mat temp = Mat(1, 3, CV_64F) ;
Mat temp;
temp = wRo_to_euler(h).clone();
//cout << "temp.rows: " << temp.rows << endl;
//cout << "temp.cols: " << temp.cols << endl;

cout << "wRo_to_euler(h): "<<temp<< endl;
system("pause");
}

``````

• 写回答

#### 1条回答默认 最新

• 爱晚乏客游 2021-07-18 03:27
关注

这就是把临时变量的引用return的结果。returnWro相当于函数内部的临时变量，如果编译器帮你保留的话，这个结果就是正确的，如果不帮你保留，那么结果就是错误的。举个例子来说

``````int& fun()
{
int i = 1;
return i;
}
int main(){
int& a = fun();
cout << a << endl;
cout << a << endl;
cout << a << endl;

}
``````

上面代码的结果，你可以看到并非你想象的那样，每次都是1，而这就是编译器只帮你做了一次保留的结果，如果有些编译器没有做保留，每次都是乱码都有可能。
而你的问题就是相当于把临时变量的引用返回了，所以就出现了这个问题。有两种方法，一种是外部传入mat引用(推荐)

``````int wRo_to_euler(Mat wRo,Mat &outImg) {
outImg=Mat(1, 3, CV_64F, returnWro_arr);
return 0;
}
//调用：
Mat temp;
wRo_to_euler(h，temp);
``````

另外一种就是return Mat.clone();但是不推荐这种写法，安全性不高

``````
Mat wRo_to_euler(Mat wRo) {
return returnWro.clone();    //returnWro的x,y,z坐标
}

``````
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

• 已采纳回答 7月21日
• 创建了问题 7月17日

#### 悬赏问题

• ¥15 w10部分软件不能联网
• ¥15 关于安装hbase的问题(操作系统-windows)