前面已经简单说明了PCL库中I/O模块所具备的基本功能,以及里面各个类的功能等。详细信息可参考:https://blog.csdn.net/CFH1021/article/details/121638948?spm=1001.2014.3001.5502
那么今天主要来说明,怎么使用I/O模块中的类或者函数接口, 来操作PCD文件,例如读操作和写操作。
#include <iostream>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
void print_cloud(pcl::PointCloud<pcl::PointXYZ> &cloud);
void read_pcd_file(std::string &file_name);
void save_pcd_file(std::string &file_name);
int main(int argc, char** argv){
int op_type;
std::cout << "input operate type(1. read pcd; 2. save pcd):" << std::endl;
std::cin >> op_type;
std::string file_name = "test.pcd";
switch (op_type){
case 1:
std::cout << "read pcd file." << std::endl;
read_pcd_file(file_name);
break;
case 2:
std::cout << "save pcd file." << std::endl;
save_pcd_file(file_name);
break;
default:
std::cerr << "Don't support this operate-type: " << op_type << std::endl;
break;
};
return 0;
}
void print_cloud(pcl::PointCloud<pcl::PointXYZ> &cloud){
std::cout << "point data: " << std::endl;
for (size_t i = 0; i < cloud.points.size(); ++i){
std::cout << "\t" << "(" << cloud.points[i].x << ", "
<< cloud.points[i].y << ", " << cloud.points[i].z
<< ")" << std::endl;
}
}
void read_pcd_file(std::string &file_name){
// 创建cloud对象
pcl::PointCloud<pcl::PointXYZ> cloud;
// 加载指定的pcd文件
int ret = pcl::io::loadPCDFile(file_name, cloud);
// 若返回值为-1,表示文件不可读
if (-1 == ret){
std::cerr << "Couldn't read file " << file_name << std::endl;
return;
}
// 打印file_name文件中的点云数据信息。
print_cloud(cloud);
}
void save_pcd_file(std::string &file_name){
// 创建cloud对象
pcl::PointCloud<pcl::PointXYZ> cloud;
srand((uint32_t)time(nullptr));
// 创建点云,并设置相应的参数
cloud.width = 5;
cloud.height = 1;
cloud.points.resize(cloud.width * cloud.height);
// 利用随机数生成的值,填充cloud
for(size_t i = 0; i < cloud.points.size(); ++i){
cloud.points[i].x = 1024 * rand() /(RAND_MAX + 1.f);
cloud.points[i].y = 1024 * rand() /(RAND_MAX + 1.f);
cloud.points[i].z = 1024 * rand() /(RAND_MAX + 1.f);
}
// 保存点云数据到file_name pcd文件中
pcl::io::savePCDFile(file_name, cloud);
// 打印保存的点云数据信息
print_cloud(cloud);
}
result:
1. save pcd file
input operate type(1. read pcd; 2. save pcd):
2
save pcd file.
point data:
(0.18826, -0.83058, -0.71974)
(-0.520344, -0.175006, -0.730038)
(0.81453, -0.0477185, 0.00141573)
(0.884914, 0.284334, 0.831102)
(0.803277, -0.854547, 0.415627)
2. read pcd file
input operate type(1. read pcd; 2. save pcd):
1
read pcd file.
point data:
(0.18826, -0.83058, -0.71974)
(-0.520344, -0.175006, -0.730038)
(0.81453, -0.0477185, 0.00141573)
(0.884914, 0.284334, 0.831102)
(0.803277, -0.854547, 0.415627)
# CMAKELists.txt文件,采用cmake的方式进行编译
cmake_minimum_required(VERSION 3.14 FATAL_ERROR)
project(pcl_test)
find_package(PCL REQUIRED)
include_directories(${PCL_INCLUDE_DIRS})
include_directories(/usr/include)
link_directories(${PCL_LIBRARY_DIRS})
add_definitions(${PCL_DEFINITIONS})
add_executable(pcl_test pcl_io_test.cpp)
target_link_libraries(pcl_test
${PCL_LIBRARIES}
boost_system
)