人体关键点识别之手部识别
人体关键点识别之手部识别
示例代码
import sys
import cv2
import mediapipe as mp
# 导入mediapipe库的相关模块
mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands
# 打开摄像头
cap = cv2.VideoCapture(0)
# 初始化MediaPipe Hands模块,设置检测和跟踪的置信度阈值
with mp_hands.Hands(
min_detection_confidence=0.9, # 检测手的置信度阈值
min_tracking_confidence=0.9) as hands: # 跟踪手的置信度阈值
while cap.isOpened():
# 读取摄像头帧
success, image = cap.read()
if not success:
print("Ignoring empty camera frame.")
# 如果是从视频中加载,可以用'break'代替'continue'
continue
# 翻转图像,以便后续以自拍视图显示,并将BGR图像转换为RGB
image = cv2.cvtColor(cv2.flip(image, 1), cv2.COLOR_BGR2RGB)
# 为了提高性能,可选地将图像标记为不可写,以通过引用传递
image.flags.writeable = False
results = hands.process(image)
# 在图像上绘制手部标注
image.flags.writeable = True
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
if results.multi_hand_landmarks:
for hand_landmarks in results.multi_hand_landmarks:
# 绘制手部关键点和连接线
mp_drawing.draw_landmarks(
image, hand_landmarks, mp_hands.HAND_CONNECTIONS)
# 显示带有手部标注的图像
cv2.imshow('MediaPipe Hands', image)
# 如果按下ESC键,退出循环
if cv2.waitKey(5) & 0xFF == 27:
break
# 释放摄像头资源
cap.release()
环境准备
我使用的是python3.10的版本,opencv使用命令行安装pip install opencv-python
,mediapipe同理。
python版本不要太高,否则会运行报错。
代码解读
调用mediapipe库,使用它的手部检测模型,设置手部模型检测置信度,从摄像头加载图片,并通过mediapipe库内置的绘制手部骨骼的函数绘制骨骼点,即可实现功能。