PiscCode构建Mediapipe 手势识别“剪刀石头布”小游戏

在计算机视觉与人机交互领域,手势识别是一个非常有趣的应用场景。本文将带你用 MediapipePython 实现一个基于摄像头的手势识别“剪刀石头布”小游戏,并展示实时手势与游戏结果。


1. 项目概述

该小游戏能够实现:

  1. 实时检测手势,包括 石头(Rock)剪刀(Scissors)布(Paper)OK手势

  2. 玩家展示 OK 手势时重置游戏。

  3. 当玩家展示 R/P/S 手势时,与电脑随机出拳进行比对,显示胜负结果。

  4. 在摄像头画面上绘制手部关键点和手势文字,同时在屏幕左上角显示电脑出拳和本轮结果。

整个项目的核心依赖:

  • mediapipe:用于手部关键点检测。

  • opencv-python:用于摄像头读取与图像显示。

  • numpy:用于手势判断的数学计算。

  • random:模拟电脑出拳。


2. 核心类:SimpleHandGestureGame

class SimpleHandGestureGame:def __init__(self, model_path="hand_landmarker.task", num_hands=1):# 初始化 Mediapipe HandLandmarkerbase_options = python.BaseOptions(model_asset_path=model_path)options = vision.HandLandmarkerOptions(base_options=base_options, num_hands=num_hands)self.detector = vision.HandLandmarker.create_from_options(options)self.computer_choice = Noneself.round_result = ""self.round_played = False

2.1 手势绘制 _draw_landmarks

def _draw_landmarks(self, rgb_image, detection_result):annotated_image = np.copy(rgb_image)if detection_result.hand_landmarks:for hand_landmarks in detection_result.hand_landmarks:proto_landmarks = landmark_pb2.NormalizedLandmarkList()proto_landmarks.landmark.extend([landmark_pb2.NormalizedLandmark(x=lm.x, y=lm.y, z=lm.z) for lm in hand_landmarks])solutions.drawing_utils.draw_landmarks(image=annotated_image,landmark_list=proto_landmarks,connections=mp.solutions.hands.HAND_CONNECTIONS,landmark_drawing_spec=solutions.drawing_styles.get_default_hand_landmarks_style(),connection_drawing_spec=solutions.drawing_styles.get_default_hand_connections_style())return annotated_image

2.2 手势识别 _judge_gesture

我们通过手指关键点的伸直状态判断手势:

  • 石头(Rock):全部手指弯曲

  • 剪刀(Scissors):食指和中指伸直,其他弯曲

  • 布(Paper):五指全部伸直

  • OK:拇指与食指形成圆圈,其余三指伸直

def _judge_gesture(self, hand_landmarks):def is_straight(tip, pip, mcp=None):if mcp:a, b, c = np.array([tip.x, tip.y]), np.array([pip.x, pip.y]), np.array([mcp.x, mcp.y])ba, bc = a - b, c - bcos_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc) + 1e-6)return np.arccos(np.clip(cos_angle, -1, 1)) * 180 / np.pi > 160else:return tip.y < pip.ythumb_straight = is_straight(hand_landmarks[4], hand_landmarks[2], hand_landmarks[1])index_straight = is_straight(hand_landmarks[8], hand_landmarks[6])middle_straight = is_straight(hand_landmarks[12], hand_landmarks[10])ring_straight = is_straight(hand_landmarks[16], hand_landmarks[14])pinky_straight = is_straight(hand_landmarks[20], hand_landmarks[18])total = sum([thumb_straight, index_straight, middle_straight, ring_straight, pinky_straight])# OK gesturethumb_tip, index_tip = np.array([hand_landmarks[4].x, hand_landmarks[4].y]), np.array([hand_landmarks[8].x, hand_landmarks[8].y])if np.linalg.norm(thumb_tip - index_tip) < 0.05 and middle_straight and ring_straight and pinky_straight:return "OK"if total == 0: return "Rock"if total == 2 and index_straight and middle_straight: return "Scissors"if total == 5: return "Paper"return "Undefined"

2.3 游戏逻辑 _play_game

def _play_game(self, player_choice):choices = ["Rock", "Scissors", "Paper"]if self.computer_choice is None:self.computer_choice = random.choice(choices)if player_choice == self.computer_choice:self.round_result = "Draw"elif (player_choice == "Rock" and self.computer_choice == "Scissors") or \(player_choice == "Scissors" and self.computer_choice == "Paper") or \(player_choice == "Paper" and self.computer_choice == "Rock"):self.round_result = "You Win"else:self.round_result = "Computer Wins"self.round_played = True

2.4 图像处理 do

最终的 do 方法负责:

  1. 读取摄像头帧

  2. 调用 Mediapipe 检测手势

  3. 绘制手部关键点和手势文字

  4. 显示电脑出拳及胜负结果

def do(self, frame, device=None):if frame is None: return Nonemp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))detection_result = self.detector.detect(mp_image)annotated = self._draw_landmarks(mp_image.numpy_view(), detection_result)# ...绘制手势文字和游戏结果...return cv2.cvtColor(annotated, cv2.COLOR_RGB2BGR)

3. 快速体验

import cv2
import numpy as np
import mediapipe as mp
from mediapipe import solutions
from mediapipe.framework.formats import landmark_pb2
from mediapipe.tasks import python
from mediapipe.tasks.python import vision
import randomclass SimpleHandGestureGame:def __init__(self, model_path="文件地址/hand_landmarker.task", num_hands=1):"""Initialize Mediapipe HandLandmarker and game state"""base_options = python.BaseOptions(model_asset_path=model_path)options = vision.HandLandmarkerOptions(base_options=base_options, num_hands=num_hands)self.detector = vision.HandLandmarker.create_from_options(options)self.computer_choice = Noneself.round_result = ""self.round_played = Falsedef _draw_landmarks(self, rgb_image, detection_result):annotated_image = np.copy(rgb_image)if detection_result.hand_landmarks:for hand_landmarks in detection_result.hand_landmarks:proto_landmarks = landmark_pb2.NormalizedLandmarkList()proto_landmarks.landmark.extend([landmark_pb2.NormalizedLandmark(x=lm.x, y=lm.y, z=lm.z) for lm in hand_landmarks])solutions.drawing_utils.draw_landmarks(image=annotated_image,landmark_list=proto_landmarks,connections=mp.solutions.hands.HAND_CONNECTIONS,landmark_drawing_spec=solutions.drawing_styles.get_default_hand_landmarks_style(),connection_drawing_spec=solutions.drawing_styles.get_default_hand_connections_style())return annotated_imagedef _judge_gesture(self, hand_landmarks):"""Determine hand gesture: Rock-Paper-Scissors + OK"""def is_straight(tip, pip, mcp=None):if mcp:a, b, c = np.array([tip.x, tip.y]), np.array([pip.x, pip.y]), np.array([mcp.x, mcp.y])ba, bc = a - b, c - bcos_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc) + 1e-6)return np.arccos(np.clip(cos_angle, -1, 1)) * 180 / np.pi > 160else:return tip.y < pip.ythumb_straight = is_straight(hand_landmarks[4], hand_landmarks[2], hand_landmarks[1])index_straight = is_straight(hand_landmarks[8], hand_landmarks[6])middle_straight = is_straight(hand_landmarks[12], hand_landmarks[10])ring_straight = is_straight(hand_landmarks[16], hand_landmarks[14])pinky_straight = is_straight(hand_landmarks[20], hand_landmarks[18])thumb, index, middle, ring, pinky = thumb_straight, index_straight, middle_straight, ring_straight, pinky_straighttotal = sum([thumb, index, middle, ring, pinky])# OK gesturethumb_tip, index_tip = np.array([hand_landmarks[4].x, hand_landmarks[4].y]), np.array([hand_landmarks[8].x, hand_landmarks[8].y])if np.linalg.norm(thumb_tip - index_tip) < 0.05 and middle and ring and pinky:return "OK"# Rock-Paper-Scissorsif total == 0:return "Rock"if total == 2 and index and middle:return "Scissors"if total == 5:return "Paper"return "Undefined"def _play_game(self, player_choice):"""Determine the result of Rock-Paper-Scissors round"""choices = ["Rock", "Scissors", "Paper"]if self.computer_choice is None:self.computer_choice = random.choice(choices)if player_choice == self.computer_choice:self.round_result = "Draw"elif (player_choice == "Rock" and self.computer_choice == "Scissors") or \(player_choice == "Scissors" and self.computer_choice == "Paper") or \(player_choice == "Paper" and self.computer_choice == "Rock"):self.round_result = "You Win"else:self.round_result = "Computer Wins"self.round_played = Truedef do(self, frame, device=None):"""Process a single frame, overlay hand gesture and game result (vertically)"""if frame is None:return Nonemp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))detection_result = self.detector.detect(mp_image)annotated = self._draw_landmarks(mp_image.numpy_view(), detection_result)gesture_display = ""if detection_result.hand_landmarks:for hand_landmarks in detection_result.hand_landmarks:gesture = self._judge_gesture(hand_landmarks)if gesture == "OK":self.computer_choice = random.choice(["Rock", "Scissors", "Paper"])self.round_result = ""self.round_played = Falsegesture_display = "Game Ready..."elif gesture in ["Rock", "Scissors", "Paper"] and not self.round_played:self._play_game(gesture)gesture_display = f"{gesture}"else:gesture_display = gestureh, w, _ = annotated.shapeindex_finger_tip = hand_landmarks[8]cx, cy = int(index_finger_tip.x * w), int(index_finger_tip.y * h)cv2.putText(annotated, gesture_display, (cx, cy - 20), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0), 2)if self.round_result:start_x, start_y, line_height = 30, 50, 40lines = [f"Computer Choice: {self.computer_choice}", f"Result: {self.round_result}"]for i, line in enumerate(lines):cv2.putText(annotated, line, (start_x, start_y + i * line_height), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3)return cv2.cvtColor(annotated, cv2.COLOR_RGB2BGR)

4. 总结

本文展示了如何用 Mediapipe HandLandmarker 快速搭建一个实时手势识别小游戏。通过关键点计算与简单逻辑判断,实现了石头、剪刀、布和 OK 手势识别,并结合游戏逻辑输出结果。

对 PiscTrace or PiscCode感兴趣?更多精彩内容请移步官网看看~🔗 PiscTrace

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/pingmian/95626.shtml
繁体地址,请注明出处:http://hk.pswp.cn/pingmian/95626.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【VoNR】VoNR 不等于 VoLTE on 5G

博主未授权任何人或组织机构转载博主任何原创文章&#xff0c;感谢各位对原创的支持&#xff01; 博主链接 本人就职于国际知名终端厂商&#xff0c;负责modem芯片研发。 在5G早期负责终端数据业务层、核心网相关的开发工作&#xff0c;目前牵头6G技术研究。 博客内容主要围绕…

计算机网络:网络设备在OSI七层模型中的工作层次和传输协议

OSI七层模型&#xff08;物理层、数据链路层、网络层、传输层、会话层、表示层、应用层&#xff09;中&#xff0c;不同网络设备因功能不同&#xff0c;工作在不同层次。以下是典型网络设备的工作层次及核心功能&#xff1a;1. 物理层&#xff08;第1层&#xff09; 核心功能&a…

RSA-e和phi不互素

1.题目import gmpy2 import libnum p 1656713884642828937525841253265560295123546793973683682208576533764344166170780019002774068042673556637515136828403375582169041170690082676778939857272304925933251736030429644277439899845034340194709105071151095131704526…

基于单片机蒸汽压力检测/蒸汽余热回收

传送门 &#x1f449;&#x1f449;&#x1f449;&#x1f449;单片机作品题目速选一览表&#x1f680; &#x1f449;&#x1f449;&#x1f449;&#x1f449;单片机作品题目功能速览&#x1f680; &#x1f525;更多文章戳&#x1f449;小新单片机-CSDN博客&#x1f68…

https 协议与 wss 协议有什么不同

HTTPS 是用于网页数据传输的安全协议&#xff0c;而 WSS 是用于实时双向通信&#xff08;如聊天、直播&#xff09;的安全协议&#xff0c;二者的设计目标、应用场景、底层逻辑均存在本质区别。以下从 7 个核心维度展开对比&#xff0c;并补充关键关联知识&#xff0c;帮助彻底…

主流分布式数据库集群选型指南

以下是关于主流分布式可扩展数据库集群的详细解析&#xff0c;涵盖技术分类、代表产品及适用场景&#xff0c;帮助您高效选型&#xff1a;一、分布式数据库核心分类 1. NewSQL 数据库&#xff08;强一致性 分布式事务&#xff09;产品开发方核心特性适用场景TiDBPingCAPHTAP架…

#T1359. 围成面积

题目描述编程计算由“*”号围成的下列图形的面积。面积计算方法是统计*号所围成的闭合曲线中水平线和垂直线交点的数目。如下图所示&#xff0c;在1010的二维数组中&#xff0c;有“*”围住了15个点&#xff0c;因此面积为15。输入1010的图形。输出输出面积。样例输入数据 10 0…

Hive on Tez/Spark 执行引擎对比与优化

在大数据开发中,Hive 已经成为最常用的数据仓库工具之一。随着业务数据规模的不断扩大,Hive 默认的 MapReduce 执行引擎 显得笨重低效。为了提升查询性能,Hive 支持了 Tez 和 Spark 作为底层执行引擎。本文将带你对比 Hive on Tez 与 Hive on Spark 的区别,并分享调优经验。…

深入理解 Next.js 的路由机制

深入理解 Next.js 的路由机制 作者&#xff1a;码力无边在上一篇文章中&#xff0c;我们成功创建并运行了第一个 Next.js 应用。当你打开项目文件夹时&#xff0c;你可能会注意到一个名为 pages 的目录。这个目录看似普通&#xff0c;但它却是 Next.js 路由系统的核心。今天&am…

modbus_tcp和modbus_rtu对比移植AT-socket,modbus_tcp杂记

modbus_rtu通信时没有连接过程&#xff0c;主机和从机各自初始化自身串口就行了&#xff0c;而rtu需要确定从机ID。注:在TCP连接中&#xff0c;不同的网卡有不同的IP&#xff0c;port对应具体的程序。/* 先读取数据 */for (i 0; i < len; i){if (pdPASS ! xQueueReceive(re…

Docker Compose 详解:从安装到使用的完整指南

在现代容器化应用开发中&#xff0c;Docker Compose 是一个不可或缺的工具&#xff0c;它能够帮助我们轻松定义和运行多容器的 Docker 应用程序。 一、什么是 Docker Compose&#xff1f; Docker Compose 是 Docker 官方提供的一个工具&#xff0c;用于定义和运行多容器 Dock…

springboot配置多数据源(mysql、hive)

MyBatis-Plus 不能也不建议同时去“控制” Hive。它从设计到实现都假定底层是 支持事务、支持标准 SQL 方言 的 关系型数据库&#xff08;MySQL、PostgreSQL、Oracle、SQL Server 等&#xff09;&#xff0c;而 Hive 两者都不完全符合。如果操作两个数据源都是mysql或者和关系数…

2025年上海市星光计划第十一届职业院校技能大赛高职组“信息安全管理与评估”赛项交换部分前6题详解(仅供参考)

1.北京总公司和南京分公司有两条裸纤采用了骨干链路配置,做必要的配置,只允许必要的Vlan 通过,不允许其他 Vlan 信息通过包含 Vlan1,禁止使用 trunk链路。 骨干链路位置​​:总公司 SW 与分公司 AC 之间的两条物理链路(Ethernet 1/0/5-6 必要 VLAN​​: •总公司:Vlan…

学习nginx location ~ .*.(js|css)?$语法规则

引言 nginx作为一款高性能的Web服务和反向代理服务&#xff0c;在网站性能优化中扮演着重要的角色。其中&#xff0c;location指令的正确配置是优化工作的关键之一。 这篇记录主要解析location ~ .*\.(js|css)?$这一特定的语法规则&#xff0c;帮助大家理解其在nginx配置中的…

Nmap网络扫描工具详细使用教程

目录 Nmap 主要功能 网络存活主机发现 (ARP Ping Scan) 综合信息收集扫描 (Stealth SYN Service OS) 全端口扫描 (Full Port Scan) NSE 漏洞脚本扫描 SMB 信息枚举 HTTP 服务深度枚举 SSH 安全审计 隐蔽扫描与防火墙规避 Nmap 主要功能 Nmap 主要有以下几个核心功能…

Spring Boot 3.x 的 @EnableAsync应用实例

语法结构使用 EnableAsync 其实就像为你的应用穿上一件时尚的外套&#xff0c;简单又高效&#xff01;只需在你的配置类上添加这个注解&#xff0c;轻松开启异步之旅。代码如下&#xff1a;想象一下&#xff0c;你的应用一瞬间变得灵活无比&#xff0c;像一个跳舞的机器人&…

Nginx Tomcat Jar包开机启动自动配置

一、Nginx配置1、创建systemd nginx 服务文件vi /usr/lib/systemd/system/nginx.service### 内容[Unit] DescriptionThe nginx HTTP and reverse proxy server Afternetwork.target[Service] Typeforking ExecStartPre/mnt/nginx/sbin/nginx -t ExecStart/mnt/nginx/sbin/nginx…

修订版!Uniapp从Vue3编译到安卓环境踩坑记录

Uniapp从Vue3编译到安卓环境踩坑记录 在使用Uniapp开发Vue3项目并编译到安卓环境时&#xff0c;我遇到了不少问题&#xff0c;现将主要踩坑点及解决方案整理如下&#xff0c;供大家参考。 1. 动态导入与静态导入问题 问题描述&#xff1a; 在Vue3项目中使用的动态导入语法在Uni…

零售消费企业的数字化增长实践,2025新版下载

当下零售消费行业&#xff0c;早不是有货就好卖的时代了。一方面&#xff0c;前两年消费市场的热度催生出大批新品牌入场&#xff0c;供给端瞬间拥挤&#xff1b;另一方面&#xff0c;消费者获取信息越来越容易&#xff0c;新潮流、新观念几天一个变化。企业想稳住增长、必须要…

[网鼎杯 2020 青龙组]AreUSerialz

BUUCTF在线评测BUUCTF 是一个 CTF 竞赛和训练平台&#xff0c;为各位 CTF 选手提供真实赛题在线复现等服务。https://buuoj.cn/challenges#[%E7%BD%91%E9%BC%8E%E6%9D%AF%202020%20%E9%9D%92%E9%BE%99%E7%BB%84]AreUSerialz启动靶机&#xff0c;页面显示php代码 <?phpincl…