跳到正文

科技·工程

Python人脸识别&&自动切换桌面(基于opencv)

enchengzhang约 10 分钟
原文
文章信息与版本

文章信息

发布
2026年3月15日
收录
2026年3月16日
更新
2026年11月17日
篇幅
约 10 分钟

版本

  1. v2当前
  2. v1
Python
import cv2
import numpy as np
import pyautogui
import time
from datetime import datetime

class FaceDetectionDesktopSwitcher:
    def __init__(self):
        # 加载人脸检测分类器
        self.face_cascade = cv2.CascadeClassifier(
            cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
        )

        # 初始化摄像头
        self.cap = cv2.VideoCapture(0)
        if not self.cap.isOpened():
            print("无法打开摄像头")
            exit()

        # 设置摄像头分辨率
        self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
        self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

        # 初始化变量
        self.last_switch_time = 0
        self.switch_cooldown = 2  # 切换冷却时间(秒)
        self.last_face_count = 0

        # Windows桌面切换快捷键
        # Win+Ctrl+左箭头 和 Win+Ctrl+右箭头 可以在虚拟桌面间切换
        self.desktop_shortcuts = {
            'next': ['win', 'ctrl', 'right'],    # 下一个桌面
            'prev': ['win', 'ctrl', 'left']      # 上一个桌面
        }

        print("人脸检测程序已启动")
        print("按 'q' 退出程序")
        print("按 's' 手动切换桌面")

    def detect_faces(self, frame):
        """检测图像中的人脸"""
        # 转换为灰度图
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # 检测人脸
        faces = self.face_cascade.detectMultiScale(
            gray,
            scaleFactor=1.1,
            minNeighbors=5,
            minSize=(30, 30)
        )

        return faces

    def draw_face_boxes(self, frame, faces):
        """在图像上绘制人脸框和计数"""
        face_count = len(faces)

        # 在右上角显示人脸个数
        text = f"Faces: {face_count}"
        font = cv2.FONT_HERSHEY_SIMPLEX
        font_scale = 1
        thickness = 2

        # 获取文本大小以确定位置
        (text_width, text_height), baseline = cv2.getTextSize(text, font, font_scale, thickness)

        # 在右上角绘制文本背景
        margin = 10
        x = frame.shape[1] - text_width - margin
        y = text_height + margin

        # 绘制黑色背景
        cv2.rectangle(frame,
                     (x - 5, y - text_height - 5),
                     (x + text_width + 5, y + 5),
                     (0, 0, 0), -1)

        # 绘制文本(根据人数改变颜色)
        color = (0, 255, 0) if face_count <= 1 else (0, 0, 255)
        cv2.putText(frame, text, (x, y), font, font_scale, color, thickness)

        # 用红色方框圈出每个人脸
        for (x, y, w, h) in faces:
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
            # 可选:在每个人脸框上方添加编号
            cv2.putText(frame, f"Person", (x, y - 10),
                       cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)

        return face_count

    def switch_desktop(self, direction='next'):
        """切换Windows桌面"""
        try:
            if direction == 'next':
                pyautogui.hotkey('win', 'ctrl', 'right')
                print(f"{datetime.now().strftime('%H:%M:%S')} - 切换到下一个桌面")
            else:
                pyautogui.hotkey('win', 'ctrl', 'left')
                print(f"{datetime.now().strftime('%H:%M:%S')} - 切换到上一个桌面")
        except Exception as e:
            print(f"切换桌面失败: {e}")

    def run(self):
        """主运行循环"""
        while True:
            # 读取摄像头帧
            ret, frame = self.cap.read()
            if not ret:
                print("无法获取摄像头画面")
                break

            # 检测人脸
            faces = self.detect_faces(frame)

            # 绘制人脸框和计数
            face_count = self.draw_face_boxes(frame, faces)

            # 添加额外信息
            current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            cv2.putText(frame, current_time, (10, 30),
                       cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)

            # 显示当前状态
            status = f"Last switch: {self.last_switch_time:.1f}s ago" if self.last_switch_time > 0 else "Ready"
            cv2.putText(frame, status, (10, 50),
                       cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)

            # 检测人数变化并触发桌面切换
            current_time_sec = time.time()
            time_since_last_switch = current_time_sec - self.last_switch_time

            # 当检测到人脸数量大于1且超过冷却时间时切换桌面
            if face_count > 1 and time_since_last_switch > self.switch_cooldown:
                # 根据人脸数量变化决定切换方向
                if face_count > self.last_face_count:
                    self.switch_desktop('next')
                elif face_count < self.last_face_count:
                    self.switch_desktop('prev')

                self.last_switch_time = current_time_sec

            # 更新上次人脸计数
            self.last_face_count = face_count

            # 显示画面
            cv2.imshow('Face Detection Desktop Switcher', frame)

            # 按键检测
            key = cv2.waitKey(1) & 0xFF
            if key == ord('q'):
                break
            elif key == ord('s'):
                # 手动切换桌面
                self.switch_desktop('next')
                self.last_switch_time = time.time()

        # 释放资源
        self.cap.release()
        cv2.destroyAllWindows()
        print("程序已退出")

def main():
    # 检查必要的库是否安装
    try:
        import pyautogui
    except ImportError:
        print("请安装必要的库:")
        print("pip install opencv-python pyautogui numpy")
        return

    # 创建并运行人脸检测程序
    switcher = FaceDetectionDesktopSwitcher()
    switcher.run()

if __name__ == "__main__":
    main()
原文