由于自己大部分的点云文件都是.asc
格式的,但最近用pcl做点云方面的研究,从asc
文件到pcd
文件手动转化太麻烦,而且效率较低,故此写一个不太成熟的python脚本实现从asc文件到pcd格式文件的转换。ps
:此脚本只适用于ASCII编码的文件,并且只适用于散乱点云
分析pcd文件的格式可知,从asc到pcd转换最根本要求就是其文件开头符合pcd格式要求,其中最主要的问题是的是如何动态设置WIDTH
和POINTS
的值,对于散乱点云,这两个值都可以表示点数
.点数的获得可用asc文件的行数表示
.
代码如下:
#coding:utf-8
import time
from sys import argv
script ,filename = argv
print (\"the input file name is:%r.\" %filename)
start = time.time()
print (\"open the file...\")
file = open(filename,\"r+\")
count = 0
#统计源文件的点数
for line in file:
count=count+1
print (\"size is %d\" %count)
file.close()
#output = open(\"out.pcd\",\"w+\")
f_prefix = filename.split(\'.\')[0]
output_filename = \'{prefix}.pcd\'.format(prefix=f_prefix)
output = open(output_filename,\"w+\")
list = [\'# .PCD v.5 - Point Cloud Data file format\\n\',\'VERSION .5\\n\',\'FIELDS x y z\\n\',\'SIZE 4 4 4\\n\',\'TYPE F F F\\n\',\'COUNT 1 1 1\\n\']
output.writelines(list)
output.write(\'WIDTH \') #注意后边有空格
output.write(str(count))
output.write(\'\\nHEIGHT\')
output.write(str(1)) #强制类型转换,文件的输入只能是str格式
output.write(\'\\nPOINTS \')
output.write(str(count))
output.write(\'\\nDATA ascii\\n\')
file1 = open(filename,\"r\")
all = file1.read()
output.write(all)
output.close()
file1.close()
end = time.time()
print (\"run time is: \", end-start)
以20万左右的点云为例,该脚本运行时间大约在0.14s左右,基本可以满足自己的需求
运行以上脚本,便可自动将example.asc
转化为example.pcd