libLAS库实现las文件的读写

       尽管libLAS库已经没有维护了。但是还是有些同学在以前的项目中需要用到libLAS库。下面就简单的用代码展示如何使用libLAS库来读写las点云数据。

(1)读las文件点云数据(这个比较简单,网上有大量的例子):

std::ifstream ifs;
ifs.open("C:\\test.las", std::ios::in | std::ios::binary);
if (!ifs)
{
	cout << "打开失败!" << endl;
}
liblas::ReaderFactory f;
liblas::Reader reader = f.CreateWithStream(ifs);
unsigned long int nbPoints = reader.GetHeader().GetPointRecordsCount();//获取las数据点的个数
cout << nbPoints << endl;
double x = 0, y = 0, z = 0;
while (reader.ReadNextPoint())//循环读取las文件中的点
{
	liblas::Point const& laspoint = reader.GetPoint();
	x = laspoint.GetX();
	y = laspoint.GetY();
	z = laspoint.GetZ();
}
ifs.close();

(2)写las文件点云数据(网上的一些例子不可用):

//建立存储文件
ofstream outPt("C:\\Desktop\\mylas.las", ios::out | ios::binary);
if (!outPt.is_open())
{
	return 0;
}
double minPt[3] = { 9999999, 9999999, 9999999 };
double maxPt[3] = { 0, 0, 0 };
// 设置文件头,点数、格式、缩放因子、偏移量
liblas::Header header;
header.SetVersionMajor(1);
header.SetVersionMinor(2);
header.SetMin(minPt[0], minPt[1], minPt[2]);
header.SetMax(maxPt[0], maxPt[1], maxPt[2]);
header.SetDataFormatId(liblas::PointFormatName::ePointFormat3);
//header.SetOffset(0, 0, 0);
header.SetScale(0.001, 0.001, 0.001);
header.SetPointRecordsCount(100);
liblas::Writer writer(outPt, header);
liblas::Point point(&header);
//写入点云
for (int j = 0; j < 100; ++j)
{
	double x = 100 * rand() / (RAND_MAX + 1.0f);
	double y = 100 * rand() / (RAND_MAX + 1.0f);
	double z = 100 * rand() / (RAND_MAX + 1.0f);
	point.SetCoordinates(x, y, z);
	writer.WritePoint(point);
}
writer.SetHeader(header);
outPt.flush();
outPt.close();

       需要注意的是header.SetPointRecordsCount(100);这个函数一定要在写入点云数据之前调用,网上的一些例子写到了后面,导致写出来的las文件为空。如:https://www.cnblogs.com/xingzhensun/p/6305802.html等等。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章