Python Mediapipe [OK手势检测]

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()

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

今天喝水了嘛.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值