Skip to content

Instantly share code, notes, and snippets.

@randomize
Last active March 27, 2024 15:33
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save randomize/a95e2db97b1277bbb49d4f2f59c08f3d to your computer and use it in GitHub Desktop.
Save randomize/a95e2db97b1277bbb49d4f2f59c08f3d to your computer and use it in GitHub Desktop.
Python script to convert *.ply to *.obj (3D formats)
'''
Simple script to convert ply to obj models
'''
from argparse import ArgumentParser
from plyfile import PlyData
def main():
parser = ArgumentParser()
parser.add_argument('ply_filename')
parser.add_argument('obj_filename')
args = parser.parse_args()
convert(PlyData.read(args.ply_filename), args.obj_filename)
def convert(ply, obj):
'''
Convert given ply data
'''
with open(obj, 'w') as f:
f.write("# OBJ file\n")
verteces = ply['vertex']
for v in verteces:
p = [v['x'], v['y'], v['z']]
c = [ v['red'] / 256 , v['green'] / 256 , v['blue'] / 256 ]
a = p + c
f.write("v %.6f %.6f %.6f %.6f %.6f %.6f \n" % tuple(a) )
for v in verteces:
n = [ v['nx'], v['ny'], v['nz'] ]
f.write("vn %.6f %.6f %.6f\n" % tuple(n))
for v in verteces:
t = [ v['s'], v['t'] ]
f.write("vt %.6f %.6f\n" % tuple(t))
if 'face' in ply:
for i in ply['face']['vertex_indices']:
f.write("f")
for j in range(i.size):
# ii = [ i[j]+1 ]
ii = [ i[j]+1, i[j]+1, i[j]+1 ]
# f.write(" %d" % tuple(ii) )
f.write(" %d/%d/%d" % tuple(ii) )
f.write("\n")
main()
@mordka
Copy link

mordka commented Jun 20, 2018

It could be PLY file's wrong format but the script writes 21 thousand lines to OBJ file and then breaks with the following error:

Traceback (most recent call last):
  File "ply2obj.py", line 52, in <module>
    main()
  File "ply2obj.py", line 16, in main
    convert(PlyData.read(args.ply_filename), args.obj_filename)
  File "ply2obj.py", line 35, in convert
    n = [ v['nx'], v['ny'], v['nz'] ]
ValueError: no field of name nx

@thollins
Copy link

Doesn't work. RealSense output file PLY would not convert.
Traceback (most recent call last):
File "D:\projects\AR\PLYtoOBJ.py", line 52, in
main()
File "D:\projects\AR\PLYtoOBJ.py", line 16, in main
convert(PlyData.read(args.ply_filename), args.obj_filename)
File "D:\projects\AR\PLYtoOBJ.py", line 35, in convert
n = [ v['nx'], v['ny'], v['nz'] ]
ValueError: no field of name nx

Must be some field not yet accounted for.
Thanks though for helping me get this far.

@assafrabin
Copy link

assafrabin commented Aug 15, 2018

I had the same issue. This is hapenning if your .ply is missing some attributes (which are mandatory in this script).

I fixed these fields to be optional. You may update your gist:
ply_to_obj.py

@rrauenza
Copy link

Anyone looking for this might also be interested in https://github.com/nschloe/meshio

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment