# 在Blender中使用代码控制人物模型的眼部动作 - 睁眼与闭眼

2022-01-24 23:03:18  阅读：82  来源： 互联网

# 在Blender中使用代码控制人物模型的眼部动作 - 睁眼与闭眼

flyfish

## 代码实现

### 关于眼部的关键点在mediapipe中的定义

``````from enum import Enum
class Eyes(Enum):
LEFT = 1
RIGHT = 2
``````

``````eye_key_indicies=[
[
# Left eye
# eye lower contour
33,
7,
163,
144,
145,
153,
154,
155,
133,
# eye upper contour (excluding corners)
246,
161,
160,
159,
158,
157,
173
],
[
# Right eye
# eye lower contour
263,
249,
390,
373,
374,
380,
381,
382,
362,
# eye upper contour (excluding corners)
466,
388,
387,
386,
385,
384,
398
]
]
``````

### 根据公式计算眼睛的纵横比

``````def eye_aspect_ratio(image_points, side):

p1, p2, p3, p4, p5, p6 = 0, 0, 0, 0, 0, 0

if side == Eyes.LEFT:

eye_key_left = FacialFeatures.eye_key_indicies[0]

p2 = np.true_divide(
np.sum([image_points[eye_key_left[10]], image_points[eye_key_left[11]]], axis=0),
2)
p3 = np.true_divide(
np.sum([image_points[eye_key_left[13]], image_points[eye_key_left[14]]], axis=0),
2)
p6 = np.true_divide(
np.sum([image_points[eye_key_left[2]], image_points[eye_key_left[3]]], axis=0),
2)
p5 = np.true_divide(
np.sum([image_points[eye_key_left[5]], image_points[eye_key_left[6]]], axis=0),
2)
p1 = image_points[eye_key_left[0]]
p4 = image_points[eye_key_left[8]]

elif side == Eyes.RIGHT:
eye_key_right = FacialFeatures.eye_key_indicies[1]

p3 = np.true_divide(
np.sum([image_points[eye_key_right[10]], image_points[eye_key_right[11]]], axis=0),
2)
p2 = np.true_divide(
np.sum([image_points[eye_key_right[13]], image_points[eye_key_right[14]]], axis=0),
2)
p5 = np.true_divide(
np.sum([image_points[eye_key_right[2]], image_points[eye_key_right[3]]], axis=0),
2)
p6 = np.true_divide(
np.sum([image_points[eye_key_right[5]], image_points[eye_key_right[6]]], axis=0),
2)
p1 = image_points[eye_key_right[8]]
p4 = image_points[eye_key_right[0]]

eye = np.linalg.norm(p2-p6) + np.linalg.norm(p3-p5)
eye /= (2 * np.linalg.norm(p1-p4) + 1e-6)

return eye
``````

### 调用eye_aspect_ratio函数

``````eye_left = FacialFeatures.eye_aspect_ratio(self.image_points, Eyes.LEFT)
eye_right = FacialFeatures.eye_aspect_ratio(self.image_points, Eyes.RIGHT)
``````

### 关于纵横比的数值如下

``````eyeBlink_L: 0.034907369694056445
``````

``````eyeBlink_L: 0.2934850903969735
``````

### 根据上述展示的数值定义一个阈值

``````eye_threshold = 0.2
if eye_left > eye_threshold:
eye_left = 0
else:
eye_left = 1

if eye_right > eye_threshold:
eye_right = 0
else:
eye_right = 1
``````

### 向模型的形态键赋值

``````shape_keys['eyeBlink_L'].value = eye_left