使用Python和MediaPipe实现手势控制音量(Win/Mac)

1. 依赖库介绍

OpenCV

OpenCV(Open Source Computer Vision Library)是一个开源的计算机视觉和机器学习软件库。它包含了数百个计算机视觉算法。

MediaPipe

MediaPipe是一个跨平台的机器学习解决方案库,可以用于实时人类姿势估计、手势识别等任务。

PyCaw

PyCaw是一个Python库,用于控制Windows上的音频设备。

Python版本

本来在Python 3.11环境中进行测试,结果一直报错,似乎是mediapipe库的问题,换了Python 3.12环境后顺利解决

安装依赖

pip install mediapipe
pip install comtypes
pip install pycaw
pip install numpy
pip install opencv-python

2. 程序结构

程序主要分为以下几个部分:

  1. 初始化MediaPipe和音量控制接口。
  2. 从摄像头获取视频流。
  3. 处理视频帧以检测手部位置和姿态。
  4. 计算手指之间的距离,并将其映射到音量控制上。
  5. 显示处理后的图像,包括手部标志和音量指示。

3. 代码详解

3.1 初始化

首先,我们需要导入必要的库,并初始化MediaPipe和音量控制接口。

import cv2
import mediapipe as mp
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
import time
import math
import numpy as np

class HandControlVolume:
    def __init__(self):
        self.mp_drawing = mp.solutions.drawing_utils
        self.mp_drawing_styles = mp.solutions.drawing_styles
        self.mp_hands = mp.solutions.hands

        devices = AudioUtilities.GetSpeakers()
        interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
        self.volume = cast(interface, POINTER(IAudioEndpointVolume))
        self.volume.SetMute(0, None)
        self.volume_range = self.volume.GetVolumeRange()

3.2 主函数

recognize函数是程序的核心,负责处理视频流并进行手势识别和音量控制。

def recognize(self):
    fpsTime = time.time()
    cap = cv2.VideoCapture(0)
    resize_w = 640
    resize_h = 480

    rect_height = 0
    rect_percent_text = 0

    with self.mp_hands.Hands(min_detection_confidence=0.7,
                             min_tracking_confidence=0.5,
                             max_num_hands=2) as hands:
        while cap.isOpened():
            success, image = cap.read()
            image = cv2.resize(image, (resize_w, resize_h))

            if not success:
                print("空帧.")
                continue

            image.flags.writeable = False
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            image = cv2.flip(image, 1)
            results = hands.process(image)

            image.flags.writeable = True
            image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

            if results.multi_hand_landmarks:
                for hand_landmarks in results.multi_hand_landmarks:
                    self.mp_drawing.draw_landmarks(
                        image,
                        hand_landmarks,
                        self.mp_hands.HAND_CONNECTIONS,
                        self.mp_drawing_styles.get_default_hand_landmarks_style(),
                        self.mp_drawing_styles.get_default_hand_connections_style())

                    landmark_list = []
                    for landmark_id, finger_axis in enumerate(hand_landmarks.landmark):
                        landmark_list.append([landmark_id, finger_axis.x, finger_axis.y, finger_axis.z])
                    if landmark_list:
                        thumb_finger_tip = landmark_list[4]
                        thumb_finger_tip_x = math.ceil(thumb_finger_tip[1] * resize_w)
                        thumb_finger_tip_y = math.ceil(thumb_finger_tip[2] * resize_h)
                        index_finger_tip = landmark_list[8]
                        index_finger_tip_x = math.ceil(index_finger_tip[1] * resize_w)
                        index_finger_tip_y = math.ceil(index_finger_tip[2] * resize_h)
                        finger_middle_point = (thumb_finger_tip_x + index_finger_tip_x) // 2, (
                                thumb_finger_tip_y + index_finger_tip_y) // 2
                        thumb_finger_point = (thumb_finger_tip_x, thumb_finger_tip_y)
                        index_finger_point = (index_finger_tip_x, index_finger_tip_y)
                        image = cv2.circle(image, thumb_finger_point, 10, (255, 0, 255), -1)
                        image = cv2.circle(image, index_finger_point, 10, (255, 0, 255), -1)
                        image = cv2.circle(image, finger_middle_point, 10, (255, 0, 255), -1)
                        image = cv2.line(image, thumb_finger_point, index_finger_point, (255, 0, 255), 5)
                        line_len = math.hypot((index_finger_tip_x - thumb_finger_tip_x),
                                              (index_finger_tip_y - thumb_finger_tip_y))

                        min_volume = self.volume_range[0]
                        max_volume = self.volume_range[1]
                        vol = np.interp(line_len, [50, 300], [min_volume, max_volume])
                        rect_height = np.interp(line_len, [50, 300], [0, 200])
                        rect_percent_text = np.interp(line_len, [50, 300], [0, 100])

                        self.volume.SetMasterVolumeLevel(vol, None)

            cv2.putText(image, str(math.ceil(rect_percent_text)) + "%", (10, 350),
                        cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 0), 3)
            image = cv2.rectangle(image, (30, 100), (70, 300), (255, 0, 0), 3)
            image = cv2.rectangle(image, (30, math.ceil(300 - rect_height)), (70, 300), (255, 0, 0), -1)

            cTime = time.time()
            fps_text = 1 / (cTime - fpsTime)
            fpsTime = cTime
            cv2.putText(image, "FPS: " + str(int(fps_text)), (10, 70),
                        cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 0), 3)
            cv2.imshow('MediaPipe Hands', image)
            if cv2.waitKey(5) & 0xFF == 27 or cv2.getWindowProperty('MediaPipe Hands', cv2.WND_PROP_VISIBLE) < 1:
                break
        cap.release()

3.3 启动程序

最后,通过实例化HandControlVolume类并调用recognize方法来启动程序。

control = HandControlVolume()
control.recognize()

3.4 测试效果

在这里插入图片描述

4. Mac版本程序

主要功能

  • 使用MediaPipe检测手部姿态。
  • 通过计算手指之间的距离来调整系统音量。
  • 使用AppleScript来控制Mac系统的音量。

Mac版本所需依赖库

pip install mediapipe
pip install numpy
pip install opencv-python
pip install applescript

代码实现

import cv2
import mediapipe as mp
from ctypes import cast, POINTER
import applescript as al
import time
import math
import numpy as np

class HandControlVolume:
    def __init__(self):
        self.mp_drawing = mp.solutions.drawing_utils
        self.mp_drawing_styles = mp.solutions.drawing_styles
        self.mp_hands = mp.solutions.hands

    def recognize(self):
        fpsTime = time.time()
        cap = cv2.VideoCapture(0)
        resize_w = 640
        resize_h = 480

        rect_height = 0
        rect_percent_text = 0

        with self.mp_hands.Hands(min_detection_confidence=0.7,
                                 min_tracking_confidence=0.5,
                                 max_num_hands=2) as hands:
            while cap.isOpened():
                success, image = cap.read()
                image = cv2.resize(image, (resize_w, resize_h))

                if not success:
                    print("空帧.")
                    continue

                image.flags.writeable = False
                image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
                image = cv2.flip(image, 1)
                results = hands.process(image)

                image.flags.writeable = True
                image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

                if results.multi_hand_landmarks:
                    for hand_landmarks in results.multi_hand_landmarks:
                        self.mp_drawing.draw_landmarks(
                            image,
                            hand_landmarks,
                            self.mp_hands.HAND_CONNECTIONS,
                            self.mp_drawing_styles.get_default_hand_landmarks_style(),
                            self.mp_drawing_styles.get_default_hand_connections_style())

                        landmark_list = []
                        for landmark_id, finger_axis in enumerate(hand_landmarks.landmark):
                            landmark_list.append([landmark_id, finger_axis.x, finger_axis.y, finger_axis.z])
                        if landmark_list:
                            thumb_finger_tip = landmark_list[4]
                            thumb_finger_tip_x = math.ceil(thumb_finger_tip[1] * resize_w)
                            thumb_finger_tip_y = math.ceil(thumb_finger_tip[2] * resize_h)
                            index_finger_tip = landmark_list[8]
                            index_finger_tip_x = math.ceil(index_finger_tip[1] * resize_w)
                            index_finger_tip_y = math.ceil(index_finger_tip[2] * resize_h)
                            finger_middle_point = (thumb_finger_tip_x + index_finger_tip_x) // 2, (
                                        thumb_finger_tip_y + index_finger_tip_y) // 2
                            thumb_finger_point = (thumb_finger_tip_x, thumb_finger_tip_y)
                            index_finger_point = (index_finger_tip_x, index_finger_tip_y)
                            image = cv2.circle(image, thumb_finger_point, 10, (255, 0, 255), -1)
                            image = cv2.circle(image, index_finger_point, 10, (255, 0, 255), -1)
                            image = cv2.circle(image, finger_middle_point, 10, (255, 0, 255), -1)
                            image = cv2.line(image, thumb_finger_point, index_finger_point, (255, 0, 255), 5)
                            line_len = math.hypot((index_finger_tip_x - thumb_finger_tip_x),
                                                  (index_finger_tip_y - thumb_finger_tip_y))

                            vol = np

.interp(line_len, [50, 300], [0, 100])
                            rect_height = np.interp(line_len, [50, 300], [0, 200])
                            rect_percent_text = np.interp(line_len, [50, 300], [0, 100])

                            al.run('set volume output volume ' + str(vol))

            cv2.putText(image, str(math.ceil(rect_percent_text)) + "%", (10, 350),
                        cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 0), 3)
            image = cv2.rectangle(image, (30, 100), (70, 300), (255, 0, 0), 3)
            image = cv2.rectangle(image, (30, math.ceil(300 - rect_height)), (70, 300), (255, 0, 0), -1)

            cTime = time.time()
            fps_text = 1 / (cTime - fpsTime)
            fpsTime = cTime
            cv2.putText(image, "FPS: " + str(int(fps_text)), (10, 70),
                        cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 0), 3)
            cv2.imshow('MediaPipe Hands', image)
            if cv2.waitKey(5) & 0xFF == 27:
                break
        cap.release()

区别分析

  1. 音量控制方式

    • Windows版本:使用PyCaw库通过COM接口控制音量。
    • Mac版本:使用AppleScript控制音量。
  2. 依赖库

    • Windows版本:依赖PyCawcomtypes库。
    • Mac版本:依赖applescript库。
  3. 代码调整

    • Mac版本注释掉了与Windows音量控制相关的代码,并替换为AppleScript命令。
    • 音量计算部分的范围从Windows的音量范围映射变为0到100的映射。
  4. 平台适配

    • Windows程序利用PyCaw库与Windows系统进行交互,而Mac程序利用AppleScript与Mac系统进行交互。
### 回答1: Python的OpenCV库和MediaPipe工具包是可以一起使用的,以实现手势识别的功能。 首先,需要在Python中安装OpenCV库和MediaPipe工具包。可以使用pip命令来安装它们: ``` pip install opencv-python pip install mediapipe ``` 安装完成后,就可以开始使用了。 首先,导入必要的库: ```python import cv2 import mediapipe as mp ``` 接下来,创建一个MediaPipe的Hand对象和一个OpenCV的VideoCapture对象,用于读取摄像头输入: ```python mp_hands = mp.solutions.hands hands = mp_hands.Hands() cap = cv2.VideoCapture(0) ``` 然后,使用一个循环来读取摄像头输入并进行手势识别: ```python while True: ret, frame = cap.read() if not ret: break frame_RGB = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) results = hands.process(frame_RGB) if results.multi_handedness: for hand_landmarks in results.multi_hand_landmarks: # 在这里可以对hand_landmarks进行处理和识别手势的操作 cv2.imshow('Gesture Recognition', frame) if cv2.waitKey(1) == ord('q'): break ``` 在循环中,首先将读取到的帧转换为RGB格式,然后使用Hands对象的process方法对该帧进行手势识别。得到的结果存储在results变量中。 在对每个检测到的手部进行循环处理时,可以使用hand_landmarks来获取该手的关键点坐标。可以根据这些关键点的位置和运动轨迹来实现手势的识别和分析。 最后,通过cv2.imshow方法显示图像,并使用cv2.waitKey方法等待用户操作。当用户按下"q"键时,循环终止,程序退出。 通过以上步骤,就可以使用Python的OpenCV库和MediaPipe工具包实现手势识别的功能了。当然,实际的手势识别算法和操作需要根据具体需求进行进一步的开发和优化。 ### 回答2: Python OpenCV和MediaPipe结合使用可以实现手势识别。首先,我们需要安装必要的库和工具,包括Python、opencv-pythonmediapipe和其他依赖项。 然后,我们可以使用MediaPipe提供的HandTracking模块来检测手部的关键点。它使用机器学习模型来识别手势,并返回手部关键点的坐标。我们可以通过OpenCV的视频捕捉模块读取摄像头的实时图像。 接下来,我们通过应用MediaPipe的HandTracking模块获取手部关键点的坐标,并使用OpenCV将这些坐标绘制到图像上,以便我们可以实时看到手部的位置和动作。 完成这些基本的设置后,我们可以定义特定的手势,例如拇指和食指的指尖接触,作为一个简单的示例。我们可以通过检查特定的关键点之间的距离和角度来识别这种手势。如果关键点之间的距离较小并且角度较小,则我们可以确定手势是拇指和食指的指尖接触。 我们可以使用类似的方法来识别其他手势,比如手掌的张开和闭合,拳头的形成等等。我们可以定义一系列规则和阈值来确定特定手势的识别。 最后,我们可以根据检测到的手势执行特定的操作。例如,当识别到拇指和食指的指尖接触时,我们可以触发相机的快门,实现手势拍照。 总之,Python的OpenCV和MediaPipe结合使用可以实现手势识别。我们可以利用MediaPipe的HandTracking模块检测手部关键点,并使用OpenCV实时绘制手势位置。通过定义特定手势的规则,我们可以识别各种手势并执行相应操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

sagima_sdu

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

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

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

打赏作者

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

抵扣说明:

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

余额充值