PCL绘制点云+法线

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

cpp 复制代码
#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;
}
相关推荐
张张努力变强14 分钟前
C++ STL string 类:常用接口 + auto + 范围 for全攻略,字符串操作效率拉满
开发语言·数据结构·c++·算法·stl
小镇敲码人18 分钟前
探索CANN框架中TBE仓库:张量加速引擎的优化之道
c++·华为·acl·cann·ops-nn
平安的平安22 分钟前
面向大模型算子开发的高效编程范式PyPTO深度解析
c++·mfc
June`24 分钟前
muduo项目排查错误+测试
linux·c++·github·muduo网络库
C++ 老炮儿的技术栈28 分钟前
VS2015 + Qt 实现图形化Hello World(详细步骤)
c语言·开发语言·c++·windows·qt
Once_day36 分钟前
C++之《Effective C++》读书总结(4)
c语言·c++·effective c++
柯一梦39 分钟前
STL2---深入探索vector的实现
c++
MSTcheng.1 小时前
【C++】C++11新特性(二)
java·开发语言·c++·c++11
愚者游世1 小时前
Delegating Constructor(委托构造函数)各版本异同
开发语言·c++·程序人生·面试·改行学it
小镇敲码人1 小时前
探索华为CANN框架中的ACL仓库
c++·python·华为·acl·cann