公司近期要求离开工位要求锁屏python写了个小demo检测人脸离开座位自动锁屏
1) 环境准备安装Python3.8,这个没什么好说的直接官网下载安装
3)安装 Cmake,这个没什么好说的直接官网下载安装
2)安装 OpenCV
sudo apt-get update
pip install opencv-python face_recognition --extra-index-url https://mirrors.aliyun.com/pypi/simple/
3)安装 Dlib,编译安装很麻烦,直接免编译安装,快速使用。Dlib是一个使用现代C++技术编写的跨平台的通用库,其中包含用于在C ++中创建复杂软件以解决实际问题的机器学习算法和工具
pip install dlib-19.19.0-cp38-cp38-win_amd64.whl
4) 安装PyQt5
pip install PyQt5
5) python demo
import sys
import cv2
from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget, QPushButton
from PyQt5.QtCore import QTimer, Qt
from PyQt5.QtGui import QImage, QPixmap
import ctypes
class FaceDetectionApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
self.cap = cv2.VideoCapture(0) # 打开默认摄像头
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_frame)
self.timer.start(1000) # 每 1 秒触发一次
self.no_face_count = 0 # 计数器,记录连续未检测到人脸的帧数
self.screen_locked = False # 标志,记录屏幕是否已经锁定
def initUI(self):
self.setWindowTitle('Face Detection with OpenCV and PyQt5')
self.setGeometry(100, 100, 800, 600)
layout = QVBoxLayout()
self.label = QLabel(self)
self.label.setAlignment(Qt.AlignCenter)
layout.addWidget(self.label)
self.face_label = QLabel("No face detected", self)
self.face_label.setAlignment(Qt.AlignCenter)
layout.addWidget(self.face_label)
self.quit_button = QPushButton('Quit', self)
self.quit_button.clicked.connect(self.close)
layout.addWidget(self.quit_button)
self.setLayout(layout)
def update_frame(self):
ret, frame = self.cap.read()
if not ret:
print("Failed to capture image")
return
# 转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 加载人脸检测器
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# 检测人脸
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
if len(faces) > 0:
self.face_label.setText("Face detected!")
self.no_face_count = 0 # 重置计数器
self.screen_locked = False
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
else:
self.face_label.setText("No face detected")
self.no_face_count += 1 # 增加计数器
if self.no_face_count >= 10: # 如果连续10帧未检测到人脸
if not self.screen_locked: # 只有在屏幕未锁定时才触发锁屏
self.lock_screen()
self.screen_locked = True # 设置屏幕已锁定标志
self.no_face_count = 0 # 重置计数器
# 将 OpenCV 图像转换为 QImage
height, width, channel = frame.shape
bytes_per_line = 3 * width
q_img = QImage(frame.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped()
# 显示图像
self.label.setPixmap(QPixmap.fromImage(q_img))
def lock_screen(self):
"""触发 Windows 锁屏"""
ctypes.windll.user32.LockWorkStation()
self.face_label.setText("Screen locked due to no face detection")
def closeEvent(self, event):
# 释放摄像头资源
if self.cap.isOpened():
self.cap.release()
# 停止并删除定时器
if self.timer.isActive():
self.timer.stop()
self.timer.deleteLater()
# 接受关闭事件
event.accept()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = FaceDetectionApp()
ex.show()
sys.exit(app.exec_())
打包好的windows安装exe文件