-
Notifications
You must be signed in to change notification settings - Fork 0
/
ply2obj.py
74 lines (57 loc) · 1.97 KB
/
ply2obj.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""
Simple script to convert ply to obj models
"""
import os
from argparse import ArgumentParser
from plyfile import PlyData
def parse_args():
parser = ArgumentParser()
parser.add_argument('ply_path')
parser.add_argument('--obj_path', default=None, required=False)
args = parser.parse_args()
return args.ply_path, args.obj_path
def ply_path_to_obj_path(ply_path):
"""
Replaces the .ply extension with .obj extension
"""
return os.path.splitext(ply_path)[0] + '.obj'
def convert(ply_path, obj_path=None):
"""
Converts the given .ply file to an .obj file
"""
obj_path = obj_path or ply_path_to_obj_path(ply_path)
ply = PlyData.read(ply_path)
with open(obj_path, 'w') as f:
f.write("# OBJ file\n")
verteces = ply['vertex']
for v in verteces:
p = [v['x'], v['y'], v['z']]
if 'red' in v and 'green' in v and 'blue' in v:
c = [v['red'] / 256, v['green'] / 256, v['blue'] / 256]
else:
c = [0, 0, 0]
a = p + c
f.write("v %.6f %.6f %.6f %.6f %.6f %.6f \n" % tuple(a))
for v in verteces:
if 'nx' in v and 'ny' in v and 'nz' in v:
n = (v['nx'], v['ny'], v['nz'])
f.write("vn %.6f %.6f %.6f\n" % n)
for v in verteces:
if 's' in v and 't' in v:
t = (v['s'], v['t'])
f.write("vt %.6f %.6f\n" % 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")
def main():
ply_path, obj_path = parse_args()
obj_path = ply_path_to_obj_path(ply_path)
convert(ply_path, obj_path)
if __name__ == '__main__':
main()