点云处理时,关使用python读写.ply文件的博客并不多,而且要么是从ply文件头部开始写起,要么是csdn收费的。所以这里写一个博客记录下。
1. 读ply文件
这个很简单,具体可以看官方文档:
代码:
首先安装plyfile库:
pip install plyfile
然后定义函数:
from plyfile import PlyData,PlyElement
def read_ply(filename):
""" read XYZ point cloud from filename PLY file """
plydata = PlyData.read(filename)
pc = plydata['vertex'].data
pc_array = np.array([[x, y, z] for x,y,z in pc])
return pc_array
2.写ply文件
这个比较麻烦,原文档说的也不是很清楚。
from plyfile import PlyData,PlyElement
def write_ply(save_path,points,text=True):
"""
save_path : path to save: '/yy/XX.ply'
pt: point_cloud: size (N,3)
"""
points = [(points[i,0], points[i,1], points[i,2]) for i in range(points.shape[0])]
vertex = np.array(points, dtype=[('x', 'f4'), ('y', 'f4'),('z', 'f4')])
el = PlyElement.describe(vertex, 'vertex', comments=['vertices'])
PlyData([el], text=text).write(save_path)
这里假定输入的点云数据是只有xyz坐标信息的(即代码中的"vertex"),没有将面元法向颜色等写进去。
如果需要的话:
再加入以下几行代码即可
face = PlyElement.describe(np.array(face_data,dtype=[......]),'face')
color = PlyElement.describe(np.array(color_data,dtype=[......]),'color')
normals = PlyElement.describe(np.array(normals_data,dtype=[......]),'normals')
# 全部写入
PlyData([point, face,color,normals]).write(save_path)
数据类型需要对应到每一个数据元素的类型。