def write_obj_with_colors_texture(obj_name, vertices, triangles, colors, texture, uv_coords): Args: obj_name: str vertices: shape = (nver, 3);triangles: shape = (ntri, 3); colors: shape = (nver, 3) (由exmaple1.mat得到) texture: shape = (256,256,3) (由uv_texture_map.jpg得到) uv_coords: shape = (nver, 3) max value<=1 (由BFM_UV.mat得到) ‘‘‘ if obj_name.split(‘.‘)[-1] != ‘obj‘: obj_name = obj_name + ‘.obj‘ mtl_name = obj_name.replace(‘.obj‘, ‘.mtl‘) texture_name = obj_name.replace(‘.obj‘, ‘_texture.png‘) triangles = triangles.copy() triangles += 1 # mesh lab start with 1 # write obj with open(obj_name, ‘w‘) as f: # first line: write mtlib(material library) s = "mtllib {}\n".format(os.path.abspath(mtl_name)) f.write(s) # write vertices #v:{x,y,z,r,g,b} for i in range(vertices.shape[0]): s = ‘v {} {} {} {} {} {}\n‘.format(vertices[i, 0], vertices[i, 1], vertices[i, 2], colors[i, 0], colors[i, 1], colors[i, 2]) f.write(s) # write uv coords #vt:{x,y} for i in range(uv_coords.shape[0]): # s = ‘vt {} {}\n‘.format(uv_coords[i,0], 1 - uv_coords[i,1]) s = ‘vt {} {}\n‘.format(uv_coords[i,0], uv_coords[i,1]) f.write(s) f.write("usemtl FaceTexture\n") # write f: ver ind/ uv ind for i in range(triangles.shape[0]): # s = ‘f {}/{} {}/{} {}/{}\n‘.format(triangles[i,0], triangles[i,0], triangles[i,1], triangles[i,1], triangles[i,2], triangles[i,2]) s = ‘f {}/{} {}/{} {}/{}\n‘.format(triangles[i,2], triangles[i,2], triangles[i,1], triangles[i,1], triangles[i,0], triangles[i,0]) f.write(s) # write mtl with open(mtl_name, ‘w‘) as f: f.write("newmtl FaceTexture\n") s = ‘map_Kd {}\n‘.format(os.path.abspath(texture_name)) # map to image f.write(s) # write texture as png io.imsave(texture_name, texture)
mtllib /home/zsl/faceswap_workspace_zsl/face3d-master/examples/results/io/numpy.mtl v 79.39030456542969 86.16109466552734 20.938037872314453 0.7569913864135742 0.5408705472946167 0.44164004921913147 v 79.43241119384766 86.39189147949219 20.96391487121582 0.7891361713409424 0.5776993036270142 0.47755759954452515 ... vt 0.2362661212682724 0.7827212810516357 vt 0.23682615160942078 0.7814681529998779 ... usemtl FaceTexture f 2/2 131/131 1/1 f 131/131 130/130 1/1 ...
v 顶点坐标(x,y,z)像素(r,g,b)
vt uv纹理坐标(x,y)
vn 法线坐标 eg:vn -0.679327 0.446122 -0.582657
f v/vt/vn v/vt/vn v/vt/vn 三角面的顶点索引(顶点坐标索引/纹理索引/法线索引)
输出的.mtl为材质文件。mtl格式为:
# 为漫反射指定颜色纹理文件 map_Kd /home/xx/results/io/numpy_texture.png # 定义一个名为 ‘xxx‘的材质 newmtl xxx # 材质的环境光(ambient color) Ka 0 0 0 # 散射光(diffuse color)用Kd Kd 0.784314 0.784314 0.784314 # 镜面光(specular color)用Ks Ks 0 0 0 # 折射值 可在0.001到10之间进行取值。若取值为1.0,光在通过物体的时候不发生弯曲。玻璃的折射率为1.5。 Ni 1 # 反射指数 定义了反射高光度。该值越高则高光越密集,一般取值范围在0~1000。 Ns 400 # 滤光透射率 Tf 1 1 1 # 渐隐指数描述 参数factor表示物体融入背景的数量,取值范围为0.0~1.0,取值为1.0表示完全不透明,取值为0.0时表示完全透明。 d 1
原文:https://www.cnblogs.com/2333333he-tui/p/10815341.html