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 分钟前
用 OpenSSL 库实现 3DES(三重DES)加密
c++·算法·ssl
LunaGeeking2 小时前
重要的城市(图论 最短路)
c++·算法·编程·图论·最短路·floyd
君鼎2 小时前
C++内存管理与编译链接
c++
liulun2 小时前
玩转 Skia 的颜色
c++
阿伍.2 小时前
【指针】(适合考研、专升本)
c++·考研·c#
了不起的杰2 小时前
[C++][设计模式] : 单例模式(饿汉和懒汉)
c++·单例模式·设计模式
1白天的黑夜13 小时前
二叉树-226.翻转链表-力扣(LeetCode)
数据结构·c++·leetcode
秋风&萧瑟3 小时前
【C++】多重继承与虚继承
开发语言·c++
说码解字3 小时前
C++ 实现环形缓冲区
开发语言·c++
go_bai3 小时前
map与set的模拟实现
开发语言·c++·笔记·学习方法