关于使用python读写ply的比较清楚的教程很少,自己也是新手,摸索中。
import plyfile
import numpy as np
filename = "fuse.ply"
write_filename = "revised_fused.ply"
with open("revised_fused.ply","rb") as f:
plydata = PlyData.read(f)
print(plydata)#头文件
print(plydata.elements[0].data[0])#第一行点
print(plydata.['vertex'])#头文件
print(plydata['vertex'].data[0])#第一行点
with open(write_filename,"rb") as f:
print("type:",type(plydata.elements[0].data))
output:
type: <class 'numpy.ndarray'>
def read_ply(filename):
plydata = PlyData.read(filename)
pc = plydata['vertex'].data
#pc_array = np.array(pc)
pc_array = np.array([[x, y, z, nx, ny, nz, r, g, b] for x, y, z, nx, ny, nz, r, g, b in pc])
#此处矩阵的所有参数都必须被拉出来,参数数量查看头文件
return pc_array
with open(filename,"r") as f:
print("check4",f.readlines()[13])
def create_output(vertices, normals, colors, filename):
normals = normals.reshape(-1,3)
colors = colors.reshape(-1, 3) #-1代表行数自动计算
vertices = vertices.reshape(-1,3)
vertices = np.hstack([vertices, normals])
vertices = np.hstack([vertices, colors])
np.savetxt(filename, vertices, fmt='%f %f %f %f %f %f %d %d %d') # 必须先写入,然后利用write()在头部插入ply header
ply_header = '''ply
format ascii 1.0
element vertex %(vert_num)d
property float x
property float y
property float z
property float nx
property float ny
property float nz
property uchar red
property uchar green
property uchar blue
end_header
'''
with open(filename, 'r+') as f:
old = f.read()
f.seek(0)
f.write(ply_header % dict(vert_num=len(vertices)))
f.write(old)
自己将点的xyz,法向量,颜色信息组织成n行3列的数组后输入函数可用