我编写了一段python代码,可以将网格序列化为ascii或二进制PLY文件。我可以在MeshLab中打开生成的ascii文件就好了。生成的二进制文件会导致MeshLab崩溃(但它只是段错误)。我也无法在Blender中打开文件。我很难理解为什么MeshLab崩溃,因为据我所知,我坚持我写的标题。这是违规代码:
def write_ply(mesh, filename, binary=True):
"""
Output the mesh object as an ASCII .ply file, or as a little endian binary file.
"""
header = "comment This file was generated by the SurfacePy library\n"
header += "element vertex {0}\n".format(len(mesh.vertices))
header += "property float x\nproperty float y\nproperty float z\n"
header += "element face {0}\n".format(len(mesh.triangles))
header += "property list uchar int vertex_indices\n"
header += "end_header\n"
with open(filename, 'wb') as file:
if binary==True:
file.write(__pack_string("ply\nformat binary_little_endian 1.0\n"))
else:
file.write(__pack_string("ply\nformat ascii 1.0\n"))
file.write(__pack_string(header))
if binary==True:
for vert in mesh.vertices:
file.write(struct.pack('<fff', vert.x, vert.y, vert.z))
for tri in mesh.triangles:
file.write(struct.pack('<Biii', ord('3'), tri.i1, tri.i3, tri.i2))
else:
for vert in mesh.vertices:
file.write(__pack_string("{0}\n".format(vert)))
for tri in mesh.triangles:
file.write(__pack_string("3 {0} {1} {2}\n".format(tri.i1, tri.i3, tri.i2)))
def __pack_string(str):
"""
Returns a bytes object of a string, in little-endian format.
"""
chars = [c.encode('utf-8') for c in str]
fmt = "<{0}".format(''.join(['c' for i in range(0, len(chars))]))
return __pack(fmt, chars)
def __pack(fmt, args):
return struct.pack(fmt, *args)
我是否错误地写了字节?
答案 0 :(得分:0)
这个实际上很难解决。我将属性列表计数类型存储为uchar
,但整数应该直接写入uchar
,而不是像我一样从char转换。
所以我应该struct.pack('<Biii', 3, ...
而不是struct.pack('<Biii', ord('3'), ...