python实现自动手势识别代码
import cv2
import mediapipe as mp
mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands
初始化mediapipe hands
hands = mp_hands.Hands(
static_image_mode=False,
max_num_hands=2,
min_detection_confidence=0.5,
min_tracking_confidence=0.5
)
开启摄像头
cap = cv2.VideoCapture(0)
while cap.isOpened():
# 读取摄像头图像
success, image = cap.read()
if not success:
print(“Ignoring empty camera frame.”)
continue
# 翻转图像,使其更符合视觉习惯
image = cv2.flip(image, 1)
# 将图像转换为RGB格式,并传给hands.process()函数
results = hands.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
# 检测到手部时,使用mediapipe hands提供的工具绘制关键点和手部连线
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)
# 按下q键退出程序
if cv2.waitKey(5) & 0xFF == ord('q'):
break
释放摄像头
cap.release()
关闭所有窗口
cv2.destroyAllWindows()
释放mediapipe hands
hands.close()