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;
}
相关推荐
__BMGT()19 分钟前
C++ QT 打开图片
前端·c++·qt
顾子茵39 分钟前
c++从入门到精通(五)--异常处理,命名空间,多继承与虚继承
开发语言·c++
YueiL2 小时前
基于RK3588的智慧农场系统开发|RS485总线|华为云IOT|node-red|MQTT
c++·物联网·华为云·rk3588·rs485
二进制人工智能2 小时前
【OpenGL学习】(二)OpenGL渲染简单图形
c++·opengl
Dream it possible!2 小时前
LeetCode 热题 100_寻找重复数(100_287_中等_C++)(技巧)(暴力解法;哈希集合;二分查找)
c++·leetcode·哈希算法
丶Darling.3 小时前
Day119 | 灵神 | 二叉树 | 二叉树的最近共公共祖先
数据结构·c++·算法·二叉树
醍醐三叶4 小时前
C++文件操作--2 二进制文件操作
开发语言·c++
li星野5 小时前
C++:C++内存管理
开发语言·c++
溟洵5 小时前
【C++ Qt】布局管理器
开发语言·c++·qt
我家大宝最可爱5 小时前
c++动态链接库
开发语言·c++