如何在 OpenMesh 中为人脸着色?

问题描述

OpenMesh 文档中没有为人脸着色的示例。我应该使用哪个函数将 fh0 着色为绿色? (我试过 mesh.set_color 但没有成功。你可以看到我对第二部分代码的尝试)

import openmesh as om
import numpy as np

mesh = om.TriMesh()

# add a a couple of vertices to the mesh
vh0 = mesh.add_vertex([0,1,0])
vh1 = mesh.add_vertex([1,0])
vh2 = mesh.add_vertex([2,0])
vh3 = mesh.add_vertex([0,-1,0])
vh4 = mesh.add_vertex([2,0])

# add a couple of faces to the mesh
fh0 = mesh.add_face(vh0,vh1,vh2)
fh1 = mesh.add_face(vh1,vh3,vh4)
fh2 = mesh.add_face(vh0,vh1)

# add another face to the mesh,this time using a list
vh_list = [vh2,vh4]
fh3 = mesh.add_face(vh_list)

#  0 ==== 2
#  |\  0 /|
#  | \  / |
#  |2  1 3|
#  | /  \ |
#  |/  1 \|
#  3 ==== 4

for face in mesh.faces():
    mesh.set_color(face,[0.67578125,0.296875,0.3515625])

om.write_mesh('test.obj',mesh)

但这给了我

IndexError: index 3 is out of bounds for axis 0 with size 3

如何在 OpenMesh 中为面添加颜色?

解决方法

有几个问题:

  1. mesh.request_face_colors()TriMesh 对象支持存储面部颜色所必需的。
  2. mesh.set_color 需要一个 Alpha 通道,因此您的颜色实际上是 [0.67578125,0.296875,0.3515625,1.]
  3. write_mesh 需要 face_color=True 参数。
  4. .obj 文件格式不支持颜色。您可以改用 .ply。

完整代码:

import openmesh as om

mesh = om.TriMesh()

# add a a couple of vertices to the mesh
vh0 = mesh.add_vertex([0,1,0])
vh1 = mesh.add_vertex([1,0])
vh2 = mesh.add_vertex([2,0])
vh3 = mesh.add_vertex([0,-1,0])
vh4 = mesh.add_vertex([2,0])

# add a couple of faces to the mesh
fh0 = mesh.add_face(vh0,vh1,vh2)
fh1 = mesh.add_face(vh1,vh3,vh4)
fh2 = mesh.add_face(vh0,vh1)

# add another face to the mesh,this time using a list
vh_list = [vh2,vh4]
fh3 = mesh.add_face(vh_list)

#  0 ==== 2
#  |\  0 /|
#  | \  / |
#  |2  1 3|
#  | /  \ |
#  |/  1 \|
#  3 ==== 4

mesh.request_face_colors()

for face in mesh.faces():
    mesh.set_color(face,[0.67578125,1.])

for face in mesh.faces():
    print(mesh.color(face))

om.write_mesh('test.obj',mesh,face_color=True)
om.write_mesh('test.ply',face_color=True)

控制台输出

[0.67578125 0.296875   0.3515625  1.        ]
[0.67578125 0.296875   0.3515625  1.        ]
[0.67578125 0.296875   0.3515625  1.        ]
[0.67578125 0.296875   0.3515625  1.        ]

test.obj 的内容

# 5 vertices,4 faces
mtllib test.mat
v 0.000000 1.000000 0.000000
v 1.000000 0.000000 0.000000
v 2.000000 1.000000 0.000000
v 0.000000 -1.000000 0.000000
v 2.000000 -1.000000 0.000000
usemtl mat0
f 1 2 3
f 2 4 5
f 1 4 2
f 3 2 5

test.ply 的内容

ply
format ascii 1.0
element vertex 5
property float x
property float y
property float z
element face 4
property list uchar int vertex_indices
property uchar red
property uchar green
property uchar blue
end_header
0 1 0
1 0 0
2 1 0
0 -1 0
2 -1 0
3 0 1 2 172 76 90
3 1 3 4 172 76 90
3 0 3 1 172 76 90
3 2 1 4 172 76 90
,

面部颜色是 OpenMesh 中的标准属性之一。

要向实体添加标准属性,只需使用适当的请求方法即可。

就您而言,它将是 mesh.request_face_colors()

引用documentation