用C++编写一个PCL可视化交互操作的简单范例
我注意到之前的代码尝试在Python环境中运行C++代码,导致语法错误。以下是修正后的完整C++代码示例,使用PCL实现可视化交互操作:
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/common/transforms.h>
#include <Eigen/Dense>
#include <iostream>// 点类型定义
using PointT = pcl::PointXYZ;
using PointCloudT = pcl::PointCloud<PointT>;int main()
{// 创建共享数据结构PointCloudT::Ptr cloud(new PointCloudT);PointCloudT::Ptr transformed_cloud(new PointCloudT);Eigen::Matrix4f transform = Eigen::Matrix4f::Identity();pcl::visualization::PCLVisualizer::Ptr viewer;// 创建立方体点云for (float x = -0.5f; x <= 0.5f; x += 0.1f) {for (float y = -0.5f; y <= 0.5f; y += 0.1f) {for (float z = -0.5f; z <= 0.5f; z += 0.1f) {cloud->push_back(PointT(x, y, z));}}}// 初始化可视化窗口viewer.reset(new pcl::visualization::PCLVisualizer("PCL Interactive Visualization"));viewer->setBackgroundColor(0, 0, 0);viewer->addCoordinateSystem(0.3);viewer->initCameraParameters();// 添加原始点云viewer->addPointCloud(cloud, "original_cloud");viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 0.8, 0.1, 0.1, "original_cloud");// 添加变换后的点云pcl::transformPointCloud(*cloud, *transformed_cloud, transform);viewer->addPointCloud(transformed_cloud, "transformed_cloud");viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 0.1, 0.8, 0.1, "transformed_cloud");// 添加键盘事件回调viewer->registerKeyboardCallback([&](const pcl::visualization::KeyboardEvent& event) -> void {if (event.getKeySym() == "Left" || event.getKeySym() == "Right" ||event.getKeySym() == "Up" || event.getKeySym() == "Down") {// 根据按键更新变换矩阵if (event.getKeySym() == "Left") {transform(0,3) -= 0.1f;} else if (event.getKeySym() == "Right") {transform(0,3) += 0.1f;} else if (event.getKeySym() == "Up") {transform(1,3) += 0.1f;} else if (event.getKeySym() == "Down") {transform(1,3) -= 0.1f;}// 应用变换pcl::transformPointCloud(*cloud, *transformed_cloud, transform);// 更新可视化viewer->updatePointCloud(transformed_cloud, "transformed_cloud");viewer->resetStoppedFlag();}});// 添加文本信息viewer->addText("Use arrow keys to move the green cube", 10, 10, "info_text");// 主循环while (!viewer->wasStopped()) {viewer->spinOnce(100);}return 0;
}
编译运行说明:
- 保存代码为
pcl_interactive.cpp - 使用以下命令编译:
g++ -std=c++11 pcl_interactive.cpp -o pcl_interactive \-lpcl_common -lpcl_visualization -lEigen3
- 运行程序:
./pcl_interactive
功能说明:
- 创建一个立方体点云作为测试数据
- 原始点云显示为红色,变换后点云显示为绿色
- 使用键盘方向键(←→↑↓)可以平移绿色立方体
- 实时显示变换后的点云位置
这个程序展示了如何使用PCL进行基本的可视化交互操作,用户可以通过键盘控制点云的移动。
