C++保存和读取txt格式的点云数据文件
在 C++ 中,保存和读取 .txt
格式的点云数据通常需要处理每一行的点坐标。每个点的数据可以存储为 3 个浮点数(例如:x, y, z
)。以下是如何实现这一功能:
1. 保存点云数据到 .txt
文件
假设点云是一个包含 pcl::PointXYZ
类型的 pcl::PointCloud
,或者你自己的格式都可以。可以使用标准的文件流来保存数据。
示例代码:save_point_cloud_to_txt.cpp
#include <iostream>
#include <fstream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>void savePointCloudToTxt(const pcl::PointCloud<pcl::PointXYZ>::Ptr& cloud, const std::string& filename) {std::ofstream file(filename);if (!file.is_open()) {std::cerr << "Failed to open file for writing: " << filename << std::endl;return;}// 遍历点云中的每个点,并写入文件for (const auto& point : cloud->points) {file << point.x << " " << point.y << " " << point.z << "\n";}file.close();std::cout << "Point cloud saved to " << filename << std::endl;
}int main() {// 创建一个点云并填充数据pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);// 添加一些示例点cloud->push_back(pcl::PointXYZ(1.0, 2.0, 3.0));cloud->push_back(pcl::PointXYZ(4.0, 5.0, 6.0));cloud->push_back(pcl::PointXYZ(7.0, 8.0, 9.0));// 保存点云到文本文件savePointCloudToTxt(cloud, "output.txt");return 0;
}
解释:
- 该代码通过
std::ofstream
打开一个文件,将每个点的x, y, z
坐标写入到文件中,每个点占一行。 output.txt
文件格式如下:1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
2. 从 .txt
文件读取点云数据
读取 .txt
格式的点云数据也使用标准的文件流 std::ifstream
。假设文件中的每行包含 3 个浮点数,分别表示点的 x
, y
, 和 z
坐标。
示例代码:load_point_cloud_from_txt.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>bool loadPointCloudFromTxt(const std::string& filename, pcl::PointCloud<pcl::PointXYZ>::Ptr& cloud) {std::ifstream file(filename);if (!file.is_open()) {std::cerr << "Failed to open file: " << filename << std::endl;return false;}std::string line;while (std::getline(file, line)) {std::stringstream ss(line);pcl::PointXYZ point;ss >> point.x >> point.y >> point.z; // 读取每行的三个浮点数// 将点添加到点云中cloud->push_back(point);}file.close();std::cout << "Point cloud loaded from " << filename << ". Total points: " << cloud->size() << std::endl;return true;
}int main() {pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);// 从文本文件加载点云if (!loadPointCloudFromTxt("output.txt", cloud)) {std::cerr << "Error loading point cloud" << std::endl;return -1;}// 打印加载的点云for (const auto& point : cloud->points) {std::cout << point.x << " " << point.y << " " << point.z << std::endl;}return 0;
}
解释:
- 使用
std::getline
逐行读取文件,并将每行的 3 个浮点数解析为pcl::PointXYZ
对象。 - 将每个读取的点添加到
cloud
对象中。 - 输出加载的点云中的每个点坐标。