使用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系统进行交互。

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

godis源码分析——database存储核心1

前言 redis的核心是数据的快速存储&#xff0c;下面就来分析一下godis的底层存储是如何实现&#xff0c;先分析单机服务。 此文采用抓大放小原则&#xff0c;先大的流程方向&#xff0c;再抓细节。 流程图 源码分析 现在以客户端连接&#xff0c;并发起set key val命令为例…

简单的SQL字符型注入

目录 注入类型 判断字段数 确定回显点 查找数据库名 查找数据库表名 查询字段名 获取想要的数据 以sqli-labs靶场上的简单SQL注入为例 注入类型 判断是数字类型还是字符类型 常见的闭合方式 ?id1、?id1"、?id1)、?id1")等&#xff0c;大多都是单引号…

微分方程的解法(Matlab)

微分方程分为刚性微分方程和非刚性微分方程&#xff0c;在数值解法中的表现和行为特性上存在显著差异。 刚性微分方程&#xff08;Stiffness Equation&#xff09;是指其数值分析的解只有在时间间隔很小时才会稳定&#xff0c;只要时间间隔略大&#xff0c;其解就会不稳定。这…

【BUG】Python3|COPY 指令合并 ts 文件为 mp4 文件时长不对(含三种可执行源代码和解决方法)

文章目录 前言源代码FFmpeg的安装1 下载2 安装 前言 参考&#xff1a; python 合并 ts 视频&#xff08;三种方法&#xff09;使用 FFmpeg 合并多个 ts 视频文件转为 mp4 格式 Windows 平台下&#xff0c;用 Python 合并 ts 文件为 mp4 文件常见的有三种方法&#xff1a; 调用…

项目范围管理-系统架构师(二十九)

1、&#xff08;重点&#xff09;软件设计包括了四个独立又相互联系的活动&#xff0c;高质量的&#xff08;&#xff09;将改善程序结构的模块划分&#xff0c;降低过程复杂度。 A程序设计 B数据设计 C算法设计 D过程设计 解析&#xff1a; 软件设计包含四个&#xff0c;…

博客前端项目学习day01

这里写自定义目录标题 登录创建项目配置环境变量&#xff0c;方便使用登录页面验证码登陆表单 在VScode上写前端&#xff0c;采用vue3。 登录 创建项目 检查node版本 node -v 创建一个新的项目 npm init vitelatest blog-front-admin 中间会弹出询问是否要安装包&#xff0c…

R语言安装devtools包失败过程总结

R语言安装devtools包时&#xff0c;遇到usethis包总是安装失败&#xff0c;现总结如下方法&#xff0c;亲测可有效 一、usethis包及cli包安装问题 首先&#xff0c;Install.packages("usethis")出现如下错误&#xff0c;定位到是这个cli包出现问题 载入需要的程辑包…

Mac和VirtualBox Ubuntu共享文件夹

1、VirtualBox中点击设置->共享文件夹 2、设置共享文件夹路径和名称&#xff08;重点来了&#xff1a;共享文件夹名称&#xff09; 3、保存设置后重启虚拟机&#xff0c;执行下面的命令 sudo mkdir /mnt/share sudo mount -t vboxsf share /mnt/share/ 注&#xff1a;shar…

.快速幂.

按位与&#xff08;Bitwise AND&#xff09;是一种二进制运算&#xff0c;它逐位对两个数的二进制表示进行运算。对于每一位&#xff0c;只有两个相应的位都为1时&#xff0c;结果位才为1&#xff1b;否则&#xff0c;结果位为0。如&#xff1a;十进制9 & 5转化为二进制&am…

基于lstm的股票Volume预测

LSTM&#xff08;Long Short-Term Memory&#xff09;神经网络模型是一种特殊的循环神经网络&#xff08;RNN&#xff09;&#xff0c;它在处理长期依赖关系方面表现出色&#xff0c;尤其适用于时间序列预测、自然语言处理&#xff08;NLP&#xff09;和语音识别等领域。以下是…

酒店管理系统小程序的设计

管理员账户功能包括&#xff1a;系统首页&#xff0c;个人中心&#xff0c;用户管理&#xff0c;酒店管理员管理&#xff0c;房间类型管理&#xff0c;房间信息管理&#xff0c;订单信息管理&#xff0c;系统管理 微信端账号功能包括&#xff1a;系统首页&#xff0c;房间信息…

智慧校园信息化大平台整体解决方案PPT(75页)

1. 教育信息化政策 教育部印发《教育信息化2.0行动计划》&#xff0c;六部门联合发布《关于推进教育新型基础设施建设构建高质量教育支撑体系的指导意见》&#xff0c;中共中央、国务院印发《中国教育现代化2035》。这些政策文件强调了教育的全面发展、面向人人、终身学习、因…

Linux vim文本编辑器

Vim&#xff08;Vi IMproved&#xff09;是一个高度可配置的文本编辑器&#xff0c;它是Vi编辑器的增强版本&#xff0c;广泛用于程序开发和系统管理。Vim不仅保留了Vi的所有功能&#xff0c;还增加了许多新特性&#xff0c;使其更加强大和灵活。 Vim操作模式 普通模式&#xf…

vue3.0 项目h5,pc端实现扫描二维码 qrcode-reader-vue3

qrcode-reader-vue3 插件简述 qrcode-reader-vue3插件&#xff0c;允许您在不离开浏览器的情况下检测和解码二维码。 &#x1f3a5; 访问设备摄像头并持续扫描传入帧。QrcodeStream&#x1f6ae; 渲染到一个空白区域&#xff0c;您可以在其中拖放要解码的图像。QrcodeDropZon…

大气热力学(8)——热力学图的应用之一

本篇文章源自我在 2021 年暑假自学大气物理相关知识时手写的笔记&#xff0c;现转化为电子版本以作存档。相较于手写笔记&#xff0c;电子版的部分内容有补充和修改。笔记内容大部分为公式的推导过程。 文章目录 8.1 复习斜 T-lnP 图上的几种线8.1.1 等温线和等压线8.1.2 干绝热…

LintCode 629 · 最小生成树【困难 并查集 Java】

题目 题目链接&#xff1a; https://www.lintcode.com/problem/629/ 思路 核心1&#xff1a;对connections进行排序&#xff0c;根据开销升序排序 核心2&#xff1a;并查集&#xff0c;合并集合&#xff0c;记录下合并的边缘 核心3&#xff1a;如果合并完后&#xff0c;集合数…

Java 中的正则表达式

转义字符由反斜杠\x组成&#xff0c;用于实现特殊功能当想取消这些特殊功能时可以在前面加上反斜杠\ 例如在Java中当\出现时是转义字符的一部分&#xff0c;具有特殊意义&#xff0c;前面加一个反斜可以取消其特殊意义&#xff0c;表示1个普通的反斜杠\&#xff0c;\\\\表示2个…

《python程序语言设计》2018版第5章第55题利用turtle黑白棋盘。可读性还是最重要的。

今天是我从2024年2月21日开始第9次做《python程序语言设计》作者梁勇 第5章 从2019年夏天的偶然了解python到2020年第一次碰到第5章第一题。彻底放弃。再到半年后重新从第一章跑到第五章&#xff0c;一遍一遍一直到今天2024.7.14日第9次刷第五章。 真的每次刷完第五章感觉好像…

【题解】42. 接雨水(动态规划 预处理)

https://leetcode.cn/problems/trapping-rain-water/description/ class Solution { public:int trap(vector<int>& height) {int n height.size();// 预处理数组vector<int> lefts(n, 0);vector<int> rights(n, 0);// 预处理记录左侧最大值lefts[0] …

Python应用 | 基于flask-restful+AntDesignVue实现的一套图书管理系统

本文将分享个人自主开发的一套图书管理系统&#xff0c;后端基于Python语言&#xff0c;采用flask-restful开发后端接口&#xff0c;前端采用VueAntDesignVue实现。对其他类似系统的实现&#xff0c;比如学生管理系统等也有一定的参考作用。有问题欢迎留言讨论~ 关注公众号&am…