python实现实时摄像头检测识别手势代码

代码语言:python

所属分类:其他

代码描述:python实现实时摄像头检测识别手势代码,可识别ok、握拳、剪刀、一、二、三手势。

代码标签: python 实时 摄像头 检测 识别 手势 代码

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

#!/usr/local/python3/bin/python3
# -*- coding: utf-8 -*
#pip install mediapipe
#pip install pillow
import cv2
import mediapipe as mp
import math
import numpy as np
from PIL import Image, ImageDraw, ImageFont

# 初始化MediaPipe
mp_hands = mp.solutions.hands
hands = mp_hands.Hands(
    static_image_mode=False,
    max_num_hands=2,
    min_detection_confidence=0.5,
    min_tracking_confidence=0.5
)
mp_draw = mp.solutions.drawing_utils

# 打开摄像头
cap = cv2.VideoCapture(0)

def cv2AddChineseText(img, text, position, textColor=(0, 255, 0), textSize=30):
    """
    在图片上添加中文文字
    """
    if (isinstance(img, np.ndarray)):  # 判断是否OpenCV图片类型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    # 创建一个可以在图片上绘制的对象
    draw = ImageDraw.Draw(img)
    # 字体的格式 这里需要替换为你系统中已安装的中文字体
    fontStyle = ImageFont.truetype("simhei.ttf", textSize, encoding="utf-8")
    # 绘制文本
    draw.text(position, text, textColor, font=fontStyle)
    # 转换回OpenCV格式
    return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)

# [前面的其他函数保持不变]
def calculate_distance(p1, p2):
    """计算两点之间的距离"""
    return math.sqrt((p1.x - p2.x)**2 + (p1.y - p2.y)**2)

def get_finger_state(finger_tip, finger_dip, finger_pip, finger_mcp):
    """
    判断手指是否伸直
    finger_tip: 指尖
    finger_dip: 第一指节
    finger_pip: 第二指节
    finger_mcp: 指根
    """
    length_tip_mcp = calculate_distance(finger_tip, finger_mcp)
    length_dip_mcp = calculate_distance(finger_dip, finger_mcp)
    return length_tip_mcp > length_dip_mcp

def recognize_gesture(hand_landmarks):
    """识别手势"""
    # [手势识别代码保持不变]
    thumb_tip = hand_landmarks.landmark[4]
    thumb_ip = hand_landmarks.landmark[3]
    thumb_mcp = hand_landmarks.landmark[2]
    
    index_tip = hand_landmarks.landmark[8]
    index_dip = hand_landmarks.landmark[7]
    index_pip = hand_landmarks.landmark[6]
    index_mcp = hand_landmarks.landmark[5]
    
    middle_tip = hand_landmarks.landmark[12]
    middle_dip = hand_landmarks.landmark[11]
    middle_pip = hand_landmarks.landmark[10]
    middle_mcp = hand_landmarks.landmark[9]
    
    ring_tip = hand_landmarks.landmark[16]
    ring_dip = hand_landmarks.landmark[15]
    ring_pip = hand_landmarks.landmark[14]
    ring_mcp = hand_land.........完整代码请登录后点击上方下载按钮下载查看

网友评论0