第10章 MediaPipe与开源手语识别实战
10.1 项目概述
本章将从零开始搭建一个完整的实时手语识别系统。系统基于MediaPipe Holistic进行全身关键点检测,使用TensorFlow LSTM进行时序手语分类,最终实现从摄像头输入到手语翻译输出的完整流水线。
10.1.1 技术栈
| 组件 |
技术选择 |
版本 |
| 手部追踪 |
MediaPipe Holistic |
0.10+ |
| 时序分类 |
TensorFlow/Keras |
2.15+ |
| 视频采集 |
OpenCV |
4.8+ |
| 数据处理 |
NumPy |
1.24+ |
| 可视化 |
Matplotlib |
3.7+ |
10.1.2 系统架构
摄像头输入
↓
OpenCV视频采集
↓
MediaPipe Holistic处理
- 手部关键点 (42个 × 3维)
- 面部关键点 (选取关键区域)
- 姿态关键点 (选取关键区域)
↓
特征向量组装
↓
滑动窗口缓存 (30帧)
↓
LSTM模型推理
↓
手语分类结果 + 置信度
↓
结果可视化
10.2 环境搭建
10.2.1 依赖安装
# 创建虚拟环境
python -m venv slr_env
source slr_env/bin/activate # Linux/Mac
# slr_env\Scripts\activate # Windows
# 安装依赖
pip install mediapipe==0.10.9
pip install tensorflow==2.15.0
pip install opencv-python==4.8.1.78
pip install numpy==1.24.3
pip install scikit-learn==1.3.2
pip install matplotlib==3.7.5
10.2.2 验证MediaPipe安装
import mediapipe as mp
import cv2
# 测试摄像头和MediaPipe
cap = cv2.VideoCapture(0)
mp_hands = mp.solutions.hands
hands = mp_hands.Hands(
static_image_mode=False,
max_num_hands=2,
min_detection_confidence=0.5,
min_tracking_confidence=0.5
)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = hands.process(rgb)
if results.multi_hand_landmarks:
for hand_landmarks in results.multi_hand_landmarks:
mp.solutions.drawing_utils.draw_landmarks(
frame, hand_landmarks, mp_hands.HAND_CONNECTIONS)
cv2.imshow('MediaPipe Test', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
10.3 数据采集模块
10.3.1 数据采集工具
import mediapipe as mp
import cv2
import numpy as np
import os
import time
class SignLanguageDataCollector:
"""手语数据采集工具"""
def __init__(self, output_dir='data'):
self.output_dir = output_dir
os.makedirs(output_dir, exist_ok=True)
# MediaPipe初始化
self.mp_holistic = mp.solutions.holistic
self.holistic = self.mp_holistic.Holistic(
min_detection_confidence=0.5,
min_tracking_confidence=0.5
)
# 采集参数
self.sequence_length = 30 # 每个样本的帧数
self.num_sequences = 30 # 每个手势的样本数
def extract_keypoints(self, results):
"""从MediaPipe结果中提取关键点"""
# 左手关键点 (21个 × 3维 = 63)
lh = np.array([[res.x, res.y, res.z]
for res in results.left_hand_landmarks.landmark]
).flatten() if results.left_hand_landmarks else np.zeros(63)
# 右手关键点 (21个 × 3维 = 63)
rh = np.array([[res.x, res.y, res.z]
for res in results.right_hand_landmarks.landmark]
).flatten() if results.right_hand_landmarks else np.zeros(63)
# 面部关键点 (选取关键区域,简化为30个点 × 3维 = 90)
if results.face_landmarks:
# 选取眉毛、眼睛、嘴巴等关键区域
key_indices = [70, 63, 105, 66, 107, # 左眉
300, 293, 334, 296, 336, # 右眉
33, 160, 158, 133, 153, 144, # 左眼
362, 385, 387, 263, 373, 380, # 右眼
61, 146, 91, 181, 84, 17, # 嘴巴
314, 405, 321, 375, 291, 409] # 嘴巴
face = np.array([[results.face_landmarks.landmark[i].x,
results.face_landmarks.landmark[i].y,
results.face_landmarks.landmark[i].z]
for i in key_indices]).flatten()
else:
face = np.zeros(90)
# 姿态关键点 (选取上半身关键点,10个 × 3维 = 30)
if results.pose_landmarks:
pose_indices = [11, 12, 13, 14, 15, 16, 23, 24, 25, 26]
pose = np.array([[results.pose_landmarks.landmark[i].x,
results.pose_landmarks.landmark[i].y,
results.pose_landmarks.landmark[i].z]
for i in pose_indices]).flatten()
else:
pose = np.zeros(30)
# 拼接所有关键点 (63+63+90+30 = 246维)
return np.concatenate([lh, rh, face, pose])
def collect_gesture(self, gesture_name, cap):
"""采集一个手语手势的数据"""
gesture_dir = os.path.join(self.output_dir, gesture_name)
os.makedirs(gesture_dir, exist_ok=True)
print(f"\n准备采集手语: {gesture_name}")
print(f"将采集 {self.num_sequences} 个样本,每个 {self.sequence_length} 帧")
print("按 's' 开始采集,按 'q' 退出")
for sequence in range(self.num_sequences):
print(f"\n样本 {sequence + 1}/{self.num_sequences}")
print("3秒后开始...")
# 倒计时
for countdown in [3, 2, 1]:
ret, frame = cap.read()
cv2.putText(frame, str(countdown), (250, 250),
cv2.FONT_HERSHEY_SIMPLEX, 5, (0, 0, 255), 10)
cv2.imshow('Data Collection', frame)
cv2.waitKey(1000)
# 采集帧
frames_data = []
for frame_num in range(self.sequence_length):
ret, frame = cap.read()
if not ret:
break
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = self.holistic.process(rgb)
keypoints = self.extract_keypoints(results)
frames_data.append(keypoints)
# 显示采集进度
cv2.putText(frame, f'Collecting: {gesture_name}', (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.putText(frame, f'Frame: {frame_num+1}/{self.sequence_length}',
(10, 70),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.imshow('Data Collection', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
return False
# 保存数据
np.save(os.path.join(gesture_dir, f'{sequence}.npy'),
np.array(frames_data))
print(f"样本 {sequence + 1} 已保存")
return True
# 使用示例
if __name__ == '__main__':
collector = SignLanguageDataCollector(output_dir='sign_data')
cap = cv2.VideoCapture(0)
gestures = ['hello', 'thanks', 'yes', 'no', 'help']
for gesture in gestures:
if not collector.collect_gesture(gesture, cap):
break
cap.release()
cv2.destroyAllWindows()
10.4 模型训练
10.4.1 数据加载与预处理
import numpy as np
from sklearn.model_selection import train_test_split
from tensorflow.keras.utils import to_categorical
import os
def load_data(data_dir, gestures, sequence_length=30):
"""加载采集的手语数据"""
sequences = []
labels = []
for idx, gesture in enumerate(gestures):
gesture_dir = os.path.join(data_dir, gesture)
if not os.path.exists(gesture_dir):
continue
for npy_file in sorted(os.listdir(gesture_dir)):
if npy_file.endswith('.npy'):
data = np.load(os.path.join(gesture_dir, npy_file))
if data.shape[0] == sequence_length:
sequences.append(data)
labels.append(idx)
X = np.array(sequences)
y = to_categorical(labels, num_classes=len(gestures))
return X, y
# 加载数据
gestures = ['hello', 'thanks', 'yes', 'no', 'help']
X, y = load_data('sign_data', gestures)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y)
print(f"训练集: {X_train.shape}, 测试集: {X_test.shape}")
print(f"特征维度: {X_train.shape[2]}")
print(f"类别数: {y_train.shape[1]}")
10.4.2 LSTM模型定义
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout, BatchNormalization
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
def build_lstm_model(input_shape, num_classes):
"""构建LSTM手语识别模型"""
model = Sequential([
# 第一层LSTM
LSTM(128, return_sequences=True,
input_shape=input_shape,
kernel_regularizer='l2'),
BatchNormalization(),
Dropout(0.3),
# 第二层LSTM
LSTM(256, return_sequences=True,
kernel_regularizer='l2'),
BatchNormalization(),
Dropout(0.3),
# 第三层LSTM
LSTM(128, return_sequences=False,
kernel_regularizer='l2'),
BatchNormalization(),
Dropout(0.3),
# 全连接层
Dense(128, activation='relu'),
Dropout(0.3),
Dense(64, activation='relu'),
Dropout(0.2),
# 输出层
Dense(num_classes, activation='softmax')
])
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
return model
# 构建模型
input_shape = (X_train.shape[1], X_train.shape[2]) # (30, 246)
num_classes = len(gestures)
model = build_lstm_model(input_shape, num_classes)
model.summary()
# 训练回调
callbacks = [
EarlyStopping(patience=20, restore_best_weights=True),
ReduceLROnPlateau(factor=0.5, patience=10, min_lr=1e-6)
]
# 训练
history = model.fit(
X_train, y_train,
validation_data=(X_test, y_test),
epochs=100,
batch_size=32,
callbacks=callbacks
)
# 评估
test_loss, test_acc = model.evaluate(X_test, y_test)
print(f"测试准确率: {test_acc:.4f}")
10.4.3 模型架构变体
除了基础LSTM,还可以尝试以下架构变体:
CNN+LSTM:
from tensorflow.keras.layers import Conv1D, MaxPooling1D
model = Sequential([
Conv1D(64, 3, activation='relu', input_shape=input_shape),
MaxPooling1D(2),
Conv1D(128, 3, activation='relu'),
MaxPooling1D(2),
LSTM(128, return_sequences=False),
Dense(64, activation='relu'),
Dense(num_classes, activation='softmax')
])
Transformer编码器:
from tensorflow.keras.layers import MultiHeadAttention, LayerNormalization
def transformer_encoder(inputs, head_size, num_heads, ff_dim, dropout=0.1):
# 多头自注意力
attention = MultiHeadAttention(
key_dim=head_size, num_heads=num_heads, dropout=dropout
)(inputs, inputs)
attention = Dropout(dropout)(attention)
x = LayerNormalization(epsilon=1e-6)(inputs + attention)
# 前馈网络
ff = Dense(ff_dim, activation='relu')(x)
ff = Dropout(dropout)(ff)
ff = Dense(inputs.shape[-1])(ff)
return LayerNormalization(epsilon=1e-6)(x + ff)
10.5 实时推理
10.5.1 实时识别系统
import mediapipe as mp
import cv2
import numpy as np
from collections import deque
class RealTimeSignRecognizer:
"""实时手语识别系统"""
def __init__(self, model_path, gestures, sequence_length=30):
self.gestures = gestures
self.sequence_length = sequence_length
# 加载模型
from tensorflow.keras.models import load_model
self.model = load_model(model_path)
# MediaPipe
self.mp_holistic = mp.solutions.holistic
self.holistic = self.mp_holistic.Holistic(
min_detection_confidence=0.5,
min_tracking_confidence=0.5
)
self.mp_drawing = mp.solutions.drawing_utils
# 帧缓存
self.frame_buffer = deque(maxlen=sequence_length)
# 识别结果平滑
self.result_buffer = deque(maxlen=5)
def extract_keypoints(self, results):
"""提取关键点(与采集模块一致)"""
lh = np.array([[res.x, res.y, res.z]
for res in results.left_hand_landmarks.landmark]
).flatten() if results.left_hand_landmarks else np.zeros(63)
rh = np.array([[res.x, res.y, res.z]
for res in results.right_hand_landmarks.landmark]
).flatten() if results.right_hand_landmarks else np.zeros(63)
if results.face_landmarks:
key_indices = [70, 63, 105, 66, 107, 300, 293, 334, 296, 336,
33, 160, 158, 133, 153, 144, 362, 385, 387, 263, 373, 380,
61, 146, 91, 181, 84, 17, 314, 405, 321, 375, 291, 409]
face = np.array([[results.face_landmarks.landmark[i].x,
results.face_landmarks.landmark[i].y,
results.face_landmarks.landmark[i].z]
for i in key_indices]).flatten()
else:
face = np.zeros(90)
if results.pose_landmarks:
pose_indices = [11, 12, 13, 14, 15, 16, 23, 24, 25, 26]
pose = np.array([[results.pose_landmarks.landmark[i].x,
results.pose_landmarks.landmark[i].y,
results.pose_landmarks.landmark[i].z]
for i in pose_indices]).flatten()
else:
pose = np.zeros(30)
return np.concatenate([lh, rh, face, pose])
def predict(self):
"""预测当前帧缓存中的手语"""
if len(self.frame_buffer) < self.sequence_length:
return None, 0.0
sequence = np.array(list(self.frame_buffer))
sequence = np.expand_dims(sequence, axis=0)
predictions = self.model.predict(sequence, verbose=0)[0]
predicted_idx = np.argmax(predictions)
confidence = predictions[predicted_idx]
return self.gestures[predicted_idx], confidence
def smooth_prediction(self, gesture, confidence):
"""平滑识别结果,减少抖动"""
if confidence > 0.7:
self.result_buffer.append(gesture)
if len(self.result_buffer) >= 3:
# 取最近5次预测中出现最多的
from collections import Counter
most_common = Counter(self.result_buffer).most_common(1)[0]
return most_common[0], most_common[1] / len(self.result_buffer)
return gesture, confidence
def run(self):
"""运行实时识别"""
cap = cv2.VideoCapture(0)
print("实时手语识别系统已启动")
print("按 'q' 退出")
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = self.holistic.process(rgb)
# 绘制关键点
self.mp_drawing.draw_landmarks(
frame, results.left_hand_landmarks,
self.mp_holistic.HAND_CONNECTIONS)
self.mp_drawing.draw_landmarks(
frame, results.right_hand_landmarks,
self.mp_holistic.HAND_CONNECTIONS)
# 提取关键点并缓存
keypoints = self.extract_keypoints(results)
self.frame_buffer.append(keypoints)
# 预测
gesture, confidence = self.predict()
if gesture and confidence > 0.5:
gesture, confidence = self.smooth_prediction(gesture, confidence)
# 显示结果
cv2.putText(frame, f'{gesture} ({confidence:.2f})',
(10, 50),
cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 255, 0), 3)
cv2.imshow('Sign Language Recognition', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
# 运行
if __name__ == '__main__':
gestures = ['hello', 'thanks', 'yes', 'no', 'help']
recognizer = RealTimeSignRecognizer('sign_model.h5', gestures)
recognizer.run()
10.6 性能优化
10.6.1 模型量化
将浮点模型转换为INT8量化模型,减少推理延迟和模型大小:
import tensorflow as tf
# 训练后量化
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_types = [tf.float16]
tflite_model = converter.convert()
# 保存量化模型
with open('sign_model_quantized.tflite', 'wb') as f:
f.write(tflite_model)
print(f"原始模型大小: {os.path.getsize('sign_model.h5') / 1024:.1f} KB")
print(f"量化模型大小: {len(tflite_model) / 1024:.1f} KB")
10.6.2 推理加速
| 优化方法 |
延迟降低 |
精度损失 |
实现难度 |
| FP16量化 |
30-40% |
<1% |
低 |
| INT8量化 |
50-60% |
1-3% |
中 |
| 模型剪枝 |
20-40% |
1-5% |
中 |
| 知识蒸馏 |
40-60% |
2-5% |
高 |
| TensorRT优化 |
60-80% |
<1% |
高 |
10.6.3 部署建议
Web端部署:
- 使用TensorFlow.js将模型转换为Web格式
- MediaPipe提供JavaScript版本,支持浏览器端推理
- WebSocket实现实时视频流处理
移动端部署:
- TensorFlow Lite支持Android和iOS
- MediaPipe原生支持移动端
- 使用GPU Delegate加速推理
边缘设备部署:
- NVIDIA Jetson系列支持TensorRT优化
- 使用ONNX Runtime进行跨平台部署
- 考虑使用模型蒸馏减小模型体积
10.7 完整项目结构
sign-language-recognition/
├── data/ # 采集的数据
│ ├── hello/
│ ├── thanks/
│ ├── yes/
│ ├── no/
│ └── help/
├── models/ # 训练的模型
│ ├── sign_model.h5
│ └── sign_model_quantized.tflite
├── src/
│ ├── collect_data.py # 数据采集
│ ├── train_model.py # 模型训练
│ ├── real_time_recognition.py # 实时识别
│ └── utils.py # 工具函数
├── requirements.txt # 依赖
└── README.md # 项目说明
本章小结
- MediaPipe Holistic提供了全身关键点检测能力,是手语识别的理想起点
- 数据采集需要标准化流程,包括倒计时、帧数控制和自动保存
- LSTM模型适合处理手语的时序特征,CNN+LSTM和Transformer是有效的变体
- 实时推理需要帧缓存和结果平滑来保证识别的稳定性
- 模型量化和推理优化可以显著降低延迟,适合边缘部署
- 完整的项目应该包含数据采集、模型训练、实时识别和性能优化四个模块