import cv2
import mediapipe as mp
import numpy as np
# 初始化MediaPipe的解决方案
mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands
# 使用默认参数初始化手部解决方案
hands = mp_hands.Hands(
static_image_mode=False,
max_num_hands=1,
min_detection_confidence=0.7,
min_tracking_confidence=0.5)
# 打开摄像头
cap = cv2.VideoCapture(0)
# OK手势的标志
ok_gesture_detected = False
# 检测OK手势的函数
def is_ok_gesture(hand_landmarks):
# 获取拇指和食指的指尖位置
thumb_tip = hand_landmarks.landmark[4]
index_tip = hand_landmarks.landmark[8]
# 计算拇指和食指指尖之间的距离
distance = np.sqrt((thumb_tip.x - index_tip.x) ** 2 + (thumb_tip.y - index_tip.y) ** 2)
# 如果距离小于某个阈值,认为是OK手势
if distance < 0.05:
# 检查中指、无名指和小指的指尖和指关节的y坐标
middle_tip = hand_landmarks.landmark[12]
middle_pip = hand_landmarks.landmark[11]
ring_tip = hand_landmarks.landmark[16]
ring_pip = hand_landmarks.landmark[15]
pinky_tip = hand_landmarks.landmark[20]
pinky_pip = hand_landmarks.landmark[19]
# 如果其他三个手指的指尖y坐标小于指关节的y坐标,认为是伸直状态
if middle_tip.y < middle_pip.y and ring_tip.y < ring_pip.y and pinky_tip.y < pinky_pip.y:
return True
return False
while cap.isOpened():
success, image = cap.read()
if not success:
print("Ignoring empty camera frame.")
continue
image = cv2.flip(image, 1)
# 将图像从BGR转换为RGB,因为MediaPipe需要RGB图像
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# 为了提高效率,可以将图像标记为不可写
image.flags.writeable = False
# 检测手势
results = hands.process(image)
# 将图像标记为可写,因为我们将要在上面绘制手势注释
image.flags.writeable = True
# 将图像从RGB转换回BGR
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
# 如果检测到手势
if results.multi_hand_landmarks:
for idx, hand_landmarks in enumerate(results.multi_hand_landmarks):
# 获取手势的标签(左手或右手)
handedness_label = results.multi_handedness[idx].classification[0].label
# 绘制手势注释
mp_drawing.draw_landmarks(
image, hand_landmarks, mp_hands.HAND_CONNECTIONS)
# 检测OK手势
if is_ok_gesture(hand_landmarks):
ok_gesture_detected = True
cv2.putText(image, f"{handedness_label} OK!", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
# 显示图像
cv2.imshow('MediaPipe Hands', image)
if cv2.waitKey(5) & 0xFF == 27:
break
hands.close()
cap.release()
cv2.destroyAllWindows()
Python Mediapipe [OK手势检测]
最新推荐文章于 2024-07-26 17:36:26 发布