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;
}
相关推荐
FMRbpm10 小时前
链表中出现的问题
数据结构·c++·算法·链表·新手入门
Elias不吃糖11 小时前
NebulaChat项目构建笔记
linux·c++·笔记·多线程
Alberta ゙11 小时前
C++初阶
开发语言·c++
温宇飞12 小时前
C++ 内存与性能优化:语言特性的开销分析与替代方案
c++
Lucis__13 小时前
从基本用法到迭代器实现—list重难点突破
c++·容器·list
努力学习的小全全13 小时前
【CCF-CSP】06-01数位之和
c++·ccf-csp
再卷也是菜14 小时前
C++篇(16)C++11(下)
c++
CS_浮鱼14 小时前
【C++进阶】智能指针
开发语言·c++
怕什么真理无穷14 小时前
C++_面试题_21_字符串操作
java·开发语言·c++
Dream it possible!14 小时前
LeetCode 面试经典 150_二叉树_二叉树展开为链表(74_114_C++_中等)
c++·leetcode·链表·面试·二叉树