PCL绘制点云+法线

发布于:2025-05-01 ⋅ 阅读:(19) ⋅ 点赞:(0)

 读取的点云ASCII码文件,每行6个数据,3维坐标+3维法向

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/io/io.h>

typedef pcl::PointXYZRGBNormal PointT;  // 使用包含法向量的点类型

int main(int argc, char** argv) {
    //if (argc != 2) {
    //    std::cerr << "Usage: " << argv[0] << " <input_txt_file>" << std::endl;
    //    return -1;
    //}

    // 1. 创建点云对象
    pcl::PointCloud<PointT>::Ptr cloud(new pcl::PointCloud<PointT>);

    // 2. 打开并读取TXT文件
    std::ifstream file("E:\\Data\\pn.txt");
    if (!file.is_open()) {
        std::cerr << "Error opening file: " << argv[1] << std::endl;
        return -1;
    }

    std::string line;
    while (std::getline(file, line)) {
        if (line.empty()) continue;

        std::istringstream iss(line);
        PointT point;

        // 读取坐标 (x,y,z) 和法向量 (nx,ny,nz)
        if (!(iss >> point.x >> point.y >> point.z
            >> point.normal_x >> point.normal_y >> point.normal_z)) {
            std::cerr << "Error parsing line: " << line << std::endl;
            continue;
        }

        // 设置点的颜色(可选)
        point.r = 255;  // 红色
        point.g = 255;  // 绿色
        point.b = 255;  // 白色

        cloud->push_back(point);
    }
    file.close();

    // 3. 设置点云属性
    cloud->width = cloud->size();
    cloud->height = 1;
    cloud->is_dense = false;

    //std::cout << "Loaded " << cloud->size() << " points from " << argv[1] << std::endl;

    // 4. 可视化点云和法向量
    pcl::visualization::PCLVisualizer viewer("Point Cloud Viewer");

    // 添加点云
    viewer.addPointCloud<PointT>(cloud, "cloud");

    // 添加法向量(每10个点显示一个法向量,避免过于密集)
    viewer.addPointCloudNormals<PointT>(cloud, 2, 1.0, "normals");

    // 设置背景色
    viewer.setBackgroundColor(0.1, 0.1, 0.1);

    // 设置点云颜色属性
    viewer.setPointCloudRenderingProperties(
        pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, "cloud");

    // 设置法线绘制的颜色属性
    viewer.setPointCloudRenderingProperties(
        pcl::visualization::PCL_VISUALIZER_COLOR,
        1.0, 0.0, 0.0,  // RGB值 (1.0,0.0,0.0)表示红色
        "normals");

    // 5. 主循环
    while (!viewer.wasStopped()) {
        viewer.spinOnce(100);
    }

    return 0;
}


网站公告

今日签到

点亮在社区的每一天
去签到