输入一个pcd点云,经过旋转平移变换,输出变换后的点云,并显示。
#include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/registration/icp.h>//icp头文件
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/point_cloud.h>
//加载一个pcd文件,进行旋转平移后,再输出
void main()
{
//创建点云指针
pcl::PointCloud<pcl::PointXYZ>::Ptr source_cloud(new pcl::PointCloud<pcl::PointXYZ>());
// 加载点云文件
pcl::io::loadPCDFile("E:/8.Industry/BodyScan/code/code_vs2015/PointCloudMatch/rabbit.pcd", *source_cloud);
std::cout << "source loaded!" << std::endl;
/* 提示: 变换矩阵工作原理 :
|-------> 变换矩阵列
| 1 0 0 x | \
| 0 1 0 y | }-> 左边是一个3阶的单位阵(无旋转)
| 0 0 1 z | /
| 0 0 0 1 | -> 这一行用不到 (这一行保持 0,0,0,1)
方法一 #1: 使用 Matrix4f
这个是“手工方法”,可以完美地理解,但容易出错!
*/
Eigen::Matrix4f transform_1 = Eigen::Matrix4f::Identity();
// 定义一个旋转矩阵 (见 https://en.wikipedia.org/wiki/Rotation_matrix)
float theta = M_PI / 4; // 弧度角
transform_1(0, 0) = cos(theta);
transform_1(0, 1) = -sin(theta);
transform_1(1, 0) = sin(theta);
transform_1(1, 1) = cos(theta);
//(行, 列)
//在 X 轴上定义一个 2.5 米的平移.
transform_1(0, 3) = 2.5;//2.5
//打印变换矩阵
printf("Method #1: using a Matrix4f\n");
std::cout << transform_1 << std::endl;
// 执行变换,并将结果保存在新创建的 transformed_cloud 中
pcl::PointCloud<pcl::PointXYZ>::Ptr transformed_cloud(new pcl::PointCloud<pcl::PointXYZ>());
pcl::transformPointCloud(*source_cloud, *transformed_cloud, transform_1);
//save
pcl::io::savePCDFileASCII("rabbit_1.pcd", *transformed_cloud); //将点云保存到PCD文件中
// 可视化
// 可视化将原始点云显示为白色,变换后的点云为红色,还设置了坐标轴、背景颜色、点显示大小
printf("\nPoint cloud colors : white = original point cloud\n"
" red = transformed point cloud\n");
pcl::visualization::PCLVisualizer viewer("Matrix transformation example");
// 为点云定义 R,G,B 颜色
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> source_cloud_color_handler(source_cloud, 255, 255, 255);
// 输出点云到查看器,使用颜色管理
viewer.addPointCloud(source_cloud, source_cloud_color_handler, "original_cloud");
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> transformed_cloud_color_handler(transformed_cloud, 230, 20, 20); // 红
viewer.addPointCloud(transformed_cloud, transformed_cloud_color_handler, "transformed_cloud");
viewer.addCoordinateSystem(1.0, "cloud", 0);
viewer.setBackgroundColor(0.05, 0.05, 0.05, 0); // 设置背景为深灰
viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, "original_cloud");
viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, "transformed_cloud");
//viewer.setPosition(800, 400); // 设置窗口位置
while (!viewer.wasStopped())
{ // 在按下 "q" 键之前一直会显示窗口
viewer.spinOnce();
}
}