chassis_ceres_solver.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. //
  2. // Created by zx on 2021/9/17.
  3. //
  4. #include "chassis_ceres_solver.h"
  5. const float CERES_PA=(100.);
  6. const float CERES_PB=(300.);
  7. const float CERES_PC=(300.);
  8. class chassis_ceres_cost
  9. {
  10. private:
  11. pcl::PointCloud<pcl::PointXYZ>::Ptr m_cloud; //点云
  12. public:
  13. chassis_ceres_cost(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud)
  14. :m_cloud(cloud)
  15. {
  16. }
  17. template<typename T>
  18. bool operator()(const T *const variable, T *residual) const
  19. {
  20. T cx = variable[0];
  21. T cy = variable[1];
  22. T w=variable[2];
  23. T h=variable[3];
  24. const T PA=T(CERES_PA);
  25. const T PB=T(CERES_PB);
  26. const T PC=T(CERES_PC);
  27. //
  28. for (int i = 0; i < m_cloud->size(); ++i)
  29. {
  30. //先平移后旋转
  31. const Eigen::Matrix<T, 2, 1> point((T(m_cloud->points[i].x)),
  32. (T(m_cloud->points[i].z)));
  33. T kx=point(0,0);
  34. T ky=point(1,0);
  35. T fx=1.0/(1.0+ceres::exp(-PA*(kx-cx+w/2.0)))-1.0/(1.0+ceres::exp(-PA*(kx-cx-w/2.0)));
  36. T fy=1.0/(1.0+ceres::exp(-PB*(ky-cy+h/2.0)))-1.0/(1.0+ceres::exp(-PC*((ky-cy)-h/2.0)));
  37. residual[i] = fx * fy; //+(50./m_cloud->size())/(w*h+1e-16);
  38. }
  39. residual[m_cloud->size()] = T(1.0) / (w * h + 1e-16);
  40. return true;
  41. }
  42. };
  43. // 公式转图片优化
  44. #include <ceres/cubic_interpolation.h>
  45. constexpr float kMinProbability = 0.01f;
  46. constexpr float kMaxProbability = 1.f - kMinProbability;
  47. constexpr float kMaxCorrespondenceCost = 1.f - kMinProbability;
  48. constexpr int kPadding = INT_MAX / 4;
  49. constexpr float resolutionx = 0.01;
  50. constexpr float resolutiony = 0.005;
  51. constexpr float inner_width = 1.2;
  52. constexpr float chassis_height = 0.14;
  53. constexpr float startx = -2.0;
  54. constexpr float starty = -0.1;
  55. constexpr float endx = 2.0;
  56. constexpr float endy = 0.3;
  57. class GridArrayAdapter
  58. {
  59. public:
  60. enum { DATA_DIMENSION = 1 };
  61. explicit GridArrayAdapter(const cv::Mat& grid) : grid_(grid) {}
  62. void GetValue(const int row, const int column, double* const value) const {
  63. if (row < kPadding || column < kPadding || row >= NumRows() - kPadding ||
  64. column >= NumCols() - kPadding) {
  65. *value = kMaxCorrespondenceCost;
  66. } else {
  67. *value = static_cast<double>(grid_.at<float>(row - kPadding, column - kPadding));
  68. }
  69. }
  70. int NumRows() const {
  71. return grid_.rows + 2 * kPadding;
  72. }
  73. int NumCols() const {
  74. return grid_.cols + 2 * kPadding;
  75. }
  76. private:
  77. const cv::Mat& grid_;
  78. };
  79. class chassis_mat_cost
  80. {
  81. private:
  82. pcl::PointCloud<pcl::PointXYZ>::Ptr m_cloud; //点云
  83. cv::Mat m_mat;
  84. public:
  85. chassis_mat_cost(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud, cv::Mat mat)
  86. :m_cloud(cloud),m_mat(mat)
  87. {
  88. }
  89. template<typename T>
  90. bool operator()(const T *const variable, T *residual) const
  91. {
  92. T cx = variable[0];
  93. T cy = variable[1];
  94. // T w_ratio = variable[2]/T(inner_width);
  95. // T h_ratio = variable[3]/T(chassis_height);
  96. const GridArrayAdapter adapter(m_mat);
  97. ceres::BiCubicInterpolator<GridArrayAdapter> interpolator(adapter);
  98. //
  99. for (int i = 0; i < m_cloud->size(); ++i)
  100. {
  101. //先平移后旋转
  102. const Eigen::Matrix<T, 2, 1> point((T(m_cloud->points[i].x)-cx),
  103. (T(m_cloud->points[i].z)-cy));
  104. T kx=(point(0,0)-T(startx)) / T(resolutionx) + T(0.5+kPadding);
  105. T ky=(point(1,0)-T(starty)) / T(resolutiony) + T(0.5+kPadding);
  106. interpolator.Evaluate(kx, ky, &residual[i]);
  107. // residual[i] = fx * fy; //+(50./m_cloud->size())/(w*h+1e-16);
  108. }
  109. // residual[m_cloud->size()] = (w_ratio - T(1.0));
  110. // residual[m_cloud->size()+1] = (h_ratio - T(1.0));
  111. return true;
  112. }
  113. // 生成debug图片
  114. void generate_mat(cv::Mat &mat, pcl::PointCloud<pcl::PointXYZ>::Ptr cloud, double *variables)
  115. {
  116. mat = m_mat.clone();
  117. // double w_ratio = variables[2] / inner_width;
  118. // double h_ratio = variables[3] / chassis_height;
  119. for (size_t i = 0; i < cloud->size(); i++)
  120. {
  121. const Eigen::Vector2d point(
  122. ((cloud->points[i].x - variables[0]) - startx) / resolutionx,
  123. ((cloud->points[i].z - variables[1]) - starty) / resolutiony);
  124. cv::circle(mat, cv::Point2d(point.y(), point.x()), 2, cv::Scalar(0.4), 1);
  125. // std::cout << point.y() << ", " << point.x() << std::endl;
  126. }
  127. }
  128. };
  129. cv::Mat chassis_ceres_solver::m_model = chassis_ceres_solver::create_mat();
  130. chassis_ceres_solver::chassis_ceres_solver(){}
  131. chassis_ceres_solver::~chassis_ceres_solver(){}
  132. /**
  133. * @description: 使用sigmoid函数寻找xoz平面平移以及内宽、底盘高度
  134. */
  135. Error_manager chassis_ceres_solver::solve(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud,double& x,double& y,double& w,double& h)
  136. {
  137. double variable[] = {x, y, w, h};
  138. /*printf("init solve x:%.3f y: %.3f wheel:%.3f width:%.3f theta : %.3f front theta: %.3f\n",
  139. variable[0], variable[1], variable[3], variable[4], variable[2], variable[5]);*/
  140. // 第二部分:构建寻优问题
  141. ceres::Problem problem;
  142. chassis_ceres_cost *cost_func = new chassis_ceres_cost(cloud);
  143. //使用自动求导,将之前的代价函数结构体传入,第一个1是输出维度,即残差的维度,第二个1是输入维度,即待寻优参数x的维度。
  144. ceres::CostFunction* cost_function =new
  145. ceres::AutoDiffCostFunction<chassis_ceres_cost, ceres::DYNAMIC, 4>(
  146. cost_func,cloud->size()+1);
  147. problem.AddResidualBlock(cost_function, new ceres::HuberLoss(1.0), variable); //向问题中添加误差项,本问题比较简单,添加一个就行。
  148. //第三部分: 配置并运行求解器
  149. ceres::Solver::Options options;
  150. options.use_nonmonotonic_steps=false;
  151. options.linear_solver_type = ceres::DENSE_QR; //配置增量方程的解法
  152. //options.logging_type = ceres::LoggingType::SILENT;
  153. options.max_num_iterations=500;
  154. options.num_threads=1;
  155. options.minimizer_progress_to_stdout = false;//输出到cout
  156. ceres::Solver::Summary summary;//优化信息
  157. ceres::Solve(options, &problem, &summary);//求解!!!
  158. double loss=summary.final_cost/(cloud->size());
  159. x=variable[0];
  160. y=variable[1];
  161. w = variable[2];
  162. h = variable[3];
  163. // printf(" loss : %f x:%.5f y:%.5f w:%.5f h:%.5f\n",
  164. // loss,variable[0],variable[1],variable[2],variable[3]);
  165. return SUCCESS;
  166. }
  167. /**
  168. * @description: 图片代替函数十倍提升优化速度
  169. */
  170. Error_manager chassis_ceres_solver::solve_mat(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud,double& x,double& y,double& w,double& h, bool update_debug_img)
  171. {
  172. // std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now();
  173. // create_mat(m_model);
  174. // cv::imshow("model", m_model);
  175. // cv::waitKey(30);
  176. std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();
  177. // std::chrono::duration<double> time_used_mat = std::chrono::duration_cast<std::chrono::duration<double>>(t1 - t0);
  178. double variable[] = {x, y, w, h};
  179. /*printf("init solve x:%.3f y: %.3f wheel:%.3f width:%.3f theta : %.3f front theta: %.3f\n",
  180. variable[0], variable[1], variable[3], variable[4], variable[2], variable[5]);*/
  181. // 第二部分:构建寻优问题
  182. ceres::Problem problem;
  183. chassis_mat_cost *cost_func = new chassis_mat_cost(cloud, m_model);
  184. //使用自动求导,将之前的代价函数结构体传入,第一个1是输出维度,即残差的维度,第二个1是输入维度,即待寻优参数x的维度。
  185. ceres::CostFunction* cost_function =new
  186. ceres::AutoDiffCostFunction<chassis_mat_cost, ceres::DYNAMIC, 2>(
  187. cost_func, cloud->size());
  188. problem.AddResidualBlock(cost_function, new ceres::HuberLoss(1.0), variable); //向问题中添加误差项,本问题比较简单,添加一个就行。
  189. //第三部分: 配置并运行求解器
  190. ceres::Solver::Options options;
  191. options.use_nonmonotonic_steps=false;
  192. options.linear_solver_type = ceres::DENSE_QR; //配置增量方程的解法
  193. //options.logging_type = ceres::LoggingType::SILENT;
  194. options.max_num_iterations=500;
  195. options.num_threads=1;
  196. options.minimizer_progress_to_stdout = false;//输出到cout
  197. ceres::Solver::Summary summary;//优化信息
  198. ceres::Solve(options, &problem, &summary);//求解!!!
  199. // std::cout << summary.BriefReport() << std::endl;
  200. double loss=summary.final_cost/(cloud->size());
  201. x = variable[0];
  202. y = variable[1];
  203. // w = variable[2];
  204. // h = variable[3];
  205. // printf(" loss : %f x:%.5f y:%.5f w:%.5f h:%.5f\n",
  206. // loss,variable[0],variable[1],variable[2],variable[3]);
  207. std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now();
  208. std::chrono::duration<double> time_used_solve = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
  209. if(update_debug_img)
  210. {
  211. // printf("midx:%.3f, midz:%.3f\n", x, y);
  212. cost_func->generate_mat(m_projected_mat, cloud, variable);
  213. cv::namedWindow("win", cv::WINDOW_FREERATIO);
  214. cv::imshow("win", m_projected_mat);
  215. cv::waitKey();
  216. }
  217. std::chrono::steady_clock::time_point t3 = std::chrono::steady_clock::now();
  218. std::chrono::duration<double> time_used_disp = std::chrono::duration_cast<std::chrono::duration<double>>(t3 - t2);
  219. // std::cout << "\ntime used for solve, display in ms: " << time_used_solve.count() << ", " << time_used_disp.count() << std::endl
  220. // << std::endl;
  221. return SUCCESS;
  222. }
  223. cv::Mat chassis_ceres_solver::create_mat()
  224. {
  225. int rows = (endx - startx) / resolutionx + 1;
  226. int cols = (endy - starty) / resolutiony + 1;
  227. if(rows<=1 || cols <=1)
  228. return cv::Mat();
  229. cv::Mat t_mat(rows, cols, CV_32FC1);
  230. for (size_t i = 0; i < rows; i++)
  231. {
  232. for (size_t j = 0; j < cols; j++)
  233. {
  234. double x = i * resolutionx + startx;
  235. double y = j * resolutiony + starty;
  236. double fx = 1.0 / (1.0 + std::exp(-CERES_PA * (x + inner_width / 2.0))) - 1.0 / (1.0 + std::exp(-CERES_PA * (x - inner_width / 2.0)));
  237. double fy = 1.0 / (1.0 + std::exp(-CERES_PB * (y + chassis_height / 2.0))) - 1.0 / (1.0 + std::exp(-CERES_PC * (y - chassis_height / 2.0)));
  238. t_mat.at<float>(i, j) = fx * fy;
  239. // std::cout << "x,y: " << x << ", " << y << "-----value: " << 1.0 / (1.0 + std::exp(-CERES_PA * (x + default_width / 2.0)))<<", "<<
  240. // 1.0 / (1.0 + std::exp(-CERES_PA * (x - default_width / 2.0))) << std::endl;
  241. // if(fx*fy>0)
  242. // std::cout << "x,y: " << x << "," << y << ", fx,fy: " << fx << ", " << fy << ", " << fx * fy << std::endl;
  243. }
  244. }
  245. cv::normalize(t_mat, t_mat, 1.0, 0.1, cv::NORM_MINMAX);
  246. // std::cout << t_mat << std::endl;
  247. // cv::namedWindow("win", cv::WINDOW_FREERATIO);
  248. // cv::imshow("win", t_mat);
  249. // cv::waitKey(0);
  250. return t_mat;
  251. }
  252. // 返回投影地图转换的点云, 便于投影到pcl视野中
  253. pcl::PointCloud<pcl::PointXYZ>::Ptr chassis_ceres_solver::get_projected_cloud()
  254. {
  255. pcl::PointCloud<pcl::PointXYZ>::Ptr t_cloud = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>);
  256. if (m_projected_mat.empty())
  257. return t_cloud;
  258. for (size_t i = 0; i < m_projected_mat.rows; i++)
  259. {
  260. for (size_t j = 0; j < m_projected_mat.cols; j++)
  261. {
  262. double x0 = (i * resolutionx + startx);
  263. t_cloud->push_back(pcl::PointXYZ());
  264. }
  265. }
  266. return t_cloud;
  267. }