基于Mediapipe的姿态识别

一.Mediapipe是什么?

MediaPipe是一个用于构建机器学习管道的框架,用于处理视频、音频等时间序列数据。

它可以进行手势识别(单手21个关键点)、人体识别(人体躯干33个关键点)等。

单手的关键点如下图所示:

 二.基于Mediapipe识别石头、剪刀、布。

思路:根据测试设置阈值,通过某些关键点之间的距离来判断。

情形1:关键点0和8、0和12、0和16、0和20之间的距离均大于等于阈值,则判定为“Paper”;

情形2:关键点0和8、0和12之间的距离大于等于阈值,且0和16、0和20之间的距离小于阈值,则判定为“Scissor”;

情形3:关键点0和8、0和12、0和16、0和20之间的距离均小于阈值,则判定为”Rock“;

其它情形:则判定为”None“。

测试环境:windows11系统,conda虚拟环境中:python -> 3.7.13,mediapipe -> 0.8.9.1、opencv-python -> 4.5.5.64、opencv-contrib-python -> 4.5.5.64

#导包
import cv2
import mediapipe as mp
import os

# 创建一个摄像头对象,用于捕获视频帧
cap = cv2.VideoCapture(0)

# 绘图模块
myDraw = mp.solutions.drawing_utils

# 手部识别模块
mpHands = mp.solutions.hands
hands = mpHands.Hands(
    static_image_mode=False, # 非图片
    max_num_hands=1, #单手检测
    min_detection_confidence=0.8,
    min_tracking_confidence=0.8
)

# 定义保存图片的文件夹和计数器
folder = os.getcwd()
counter = 0

# 自定义函数:返回关键点之间的距离
def distance(m, n):
    return ((n.x-m.x)**2+(n.y-m.y)**2)**0.5

while True:
    success, img = cap.read()
    img = cv2.flip(img, 1)

    results = hands.process(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    if results.multi_hand_landmarks:
        for handLms in results.multi_hand_landmarks:

            # 判断手势的代码
            base = 0.3 # 辅助以判断手势

            distance_0_5 = distance(handLms.landmark[0], handLms.landmark[5]) # 0和5号关键点之间的距离
            distance_0_8 = distance(handLms.landmark[0], handLms.landmark[8])
            distance_0_12 = distance(handLms.landmark[0], handLms.landmark[12])
            distance_0_16 = distance(handLms.landmark[0], handLms.landmark[16])
            distance_0_20 = distance(handLms.landmark[0], handLms.landmark[20])

            gesture = "None"
            if distance_0_8 >= base and distance_0_12 >= base and distance_0_16 < base and distance_0_20 < base:
                gesture = "Scissor"
            if distance_0_8 >= base and distance_0_12 >= base and distance_0_16 >= base and distance_0_20 >= base:
                gesture = "Paper"
            if distance_0_8 < base and distance_0_12 < base and distance_0_16 < base and distance_0_20 < base:
                gesture = "Rock"

            cv2.putText(img, gesture, (50, 50), 0, 1, (0, 0, 255), 2)

            myDraw.draw_landmarks(img, handLms, mpHands.HAND_CONNECTIONS)

    # 可视化窗口
    cv2.imshow('Mediapipe Hands', img)

    key = cv2.waitKey(1)
    if key == ord('s'):
        counter += 1
        temp = str(counter)
        cv2.imwrite(f'{folder}/{temp}.jpg', img)
    elif key == ord('p'):
        break

# 释放摄像头
cap.release()
cv2.destroyAllWindows()

三.小结

结果展示如下:

 这个小Demo基本可以识别石头剪刀布的手势,但阈值是根据调试代码设置的,可能会由于手距摄像头的距离不同而产生识别不准确的结果。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值