我再次寻求您的帮助。我想用python制作一个脚本,该脚本采用.obj格式的顶点和法线文件,并导出2个文件的顶点坐标和另一个法线坐标。
v 1.900470 2.777519 -1.000000
v 1.900470 2.777519 -3.000000
v 2.095561 2.796734 -1.000000
v 2.095560 2.796734 -3.000000
v 2.283154 2.853640 -1.000000
v 2.283154 2.853640 -3.000000
v 2.456040 2.946049 -1.000000
v 2.456040 2.946049 -3.000000
v 2.607577 3.070412 -1.000000
vn 0.0980 -0.9952 0.0000
vn 0.2903 -0.9569 -0.0000
vn 0.4714 -0.8819 0.0000
f 2//1 3//1 1//1
f 4//2 5//2 3//2
f 6//3 7//3 5//3
并以以下格式导出它们:
变身
verxex1.x,verxex1.y,verxex1.z, verxex2.x,verxex2.y,verxex2.z,verxex3.x,verxex3.y,verxex3.z,
法线:
normal1.x,normal1.y,normal1.z, normal2.x,normal2.y,normal2.z, normal3.x,normal3.y,normal3.z,
带有出现的面孔顺序。希望我能得到一些示例代码(如果有人已经实现了)以节省一些时间。
非常感谢您!
答案 0 :(得分:1)
如果要解析Wavefront .obj file,则可以使用Regular Expression解析文件,该文件将获取包含相关数据的文件行:
import re
reComp = re.compile("(?<=^)(v |vn |vt |f )(.*)(?=$)", re.MULTILINE)
with open(filename) as f:
data = [txt.group() for txt in reComp.finditer(f.read())]
字符串列表可以转换为浮点坐标和属性以及整数索引的列表:
v_arr, vn_arr, vt_arr, f_arr = [], [], [], []
for line in data:
tokens = line.split(' ')
if tokens[0] == 'v':
v_arr.append([float(c) for c in tokens[1:]])
elif tokens[0] == 'vn':
vn_arr.append([float(c) for c in tokens[1:]])
elif tokens[0] == 'vt':
vn_arr.append([float(c) for c in tokens[1:]])
elif tokens[0] == 'f':
f_arr.append([[int(i) if len(i) else 0 for i in c.split('/')] for c in tokens[1:]])
最后生成顶点坐标和法线向量的线性化列表:
vertices, normals = [], []
for face in f_arr:
for tp in face:
vertices += v_arr[tp[0]-1]
normals += vn_arr[tp[2]-1]
使用上面的代码解析问题的Wavefront文件将生成以下顶点坐标和法向矢量数组:
顶点坐标:
[1.90047,2.777519,-3.0,2.095561,2.796734,-1.0,1.90047,2.777519,-1.0,2.09556,2.796734,-3.0,2.283154,2.85364,-1.0,2.095561,2.796734,-1.0,2.283154,2.85364, -3.0,2.45604,2.946049,-1.0,2.283154,2.85364,-1.0]
法线向量:
[0.098,-0.9952,0.0,0.098,-0.9952,0.0,0.098,-0.9952,0.0,0.2903,-0.9569,-0.0,0.2903,-0.9569,-0.0,0.2903,-0.9569,-0.0,0.4714 ,-0.8819,0.0,0.4714,-0.8819,0.0,0.4714,-0.8819,0.0]