内容由 AI 生成clickable Avatar: undefined豆包,请使用python语言YOLO帮我写一个手势识别系统,录像里面出现的一个“OK”手势,帮我print输出“OK”两个字
内容由 AI 生成
![]()
豆包,请使用python语言YOLO帮我写一个手势识别系统,录像里面出现的一个“OK”手势,帮我print输出“OK”两个字母
下面是一个基于 YOLOv8 的手势识别系统,它能够实时检测视频流中的 "OK" 手势并输出 "OK"。这个实现使用了预训练的手势识别模型,并提供了摄像头实时检测和视频文件检测两种模式。
基于YOLOv8的手势识别系统
V1
创建时间:15:25
使用说明:
- 首先需要安装必要的依赖库:
pip install ultralytics opencv-python - 运行程序后,你可以选择从摄像头实时检测或从视频文件检测
- 当检测到 "OK" 手势时,控制台会打印 "OK"
- 按 'q' 键可以退出检测程序
注意事项:
- 程序使用了预训练的 YOLOv8 手势识别模型,你需要确保模型文件正确放置
- 系统包含冷却机制,避免短时间内重复检测同一手势
- 如果需要更高的检测精度,可以考虑使用更大的 YOLO 模型或自行训练模型
-
import cv2
from ultralytics import YOLO
import timeclass GestureDetector:
def __init__(self, model_path='hands_yolov8n.pt'):
"""初始化手势识别器"""
self.model = YOLO(model_path)
self.gesture_classes = {
0: "Fist",
1: "L",
2: "Okay",
3: "Palm",
4: "Peace"
}
self.last_detection_time = 0
self.detection_cooldown = 1.0 # 检测冷却时间(秒)def detect_ok_gesture(self, frame):
"""检测OK手势"""
results = self.model(frame, classes=[2]) # 只检测OK手势(类别2)
# 检查是否检测到OK手势
if len(results) > 0 and len(results[0].boxes) > 0:
current_time = time.time()
# 冷却机制,避免重复输出
if current_time - self.last_detection_time > self.detection_cooldown:
self.last_detection_time = current_time
print("OK")
annotated_frame = results[0].plot()
return annotated_frame
return framedef run_on_camera(self, camera_id=0):
"""从摄像头进行实时检测"""
cap = cv2.VideoCapture(camera_id)
if not cap.isOpened():
print("无法打开摄像头")
return
print("按 'q' 键退出检测")
while True:
ret, frame = cap.read()
if not ret:
print("无法获取帧")
break
processed_frame = self.detect_ok_gesture(frame)
cv2.imshow('OK Gesture Detector', processed_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()def run_on_video(self, video_path):
"""从视频文件进行检测"""
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print("无法打开视频文件")
return
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(f"视频帧率: {fps} FPS")
print("按 'q' 键退出检测")
while True:
ret, frame = cap.read()
if not ret:
break
processed_frame = self.detect_ok_gesture(frame)
cv2.imshow('OK Gesture Detector', processed_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()if __name__ == "__main__":
# 下载预训练模型(如果不存在)
try:
detector = GestureDetector()
except Exception as e:
print(f"模型加载失败: {e}")
print("请确保已下载YOLOv8手势识别模型,并将路径正确设置")
exit()
# 选择检测模式
print("请选择检测模式:")
print("1. 摄像头实时检测")
print("2. 视频文件检测")
choice = input("请输入选项 (1/2): ")
if choice == '1':
camera_id = int(input("请输入摄像头ID (默认0): ") or "0")
detector.run_on_camera(camera_id)
elif choice == '2':
video_path = input("请输入视频文件路径: ")
detector.run_on_video(video_path)
else:
print("无效的选择")
更多推荐



所有评论(0)