参考文献:
1、python face_recognition实现人脸识别系统_python facerecognition检测人脸-CSDN博客
2、cv2.VideoCapture()_cv2.videocapture(0)-CSDN博客
1、camera.py文件代码如下;目录如下
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QVBoxLayout
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtCore import QTimer
import cv2
import face_recognition
import osclass VideoPlayer(QWidget):def __init__(self):super().__init__()self.initUI()def initUI(self):self.setWindowTitle("Video Player")self.setGeometry(100, 100, 800, 600)# 创建显示视频的标签self.label = QLabel(self)self.label.resize(640, 480)self.label.move(80, 40)# 创建按钮self.button = QPushButton('Play/Stop', self)self.button.move(350, 550)self.button.clicked.connect(self.toggle_video)# 加载已知人脸数据self.known_faces = {}for person_name in os.listdir("known_faces"):person_dir = os.path.join("known_faces", person_name)if os.path.isdir(person_dir):person_faces = []for filename in os.listdir(person_dir):image_path = os.path.join(person_dir, filename)image = face_recognition.load_image_file(image_path)encoding = face_recognition.face_encodings(image)[0]person_faces.append(encoding)self.known_faces[person_name] = person_faces# 初始化摄像头self.video_capture = cv2.VideoCapture(0)# 设置定时器,每隔33毫秒刷新一次self.timer = QTimer(self)self.timer.timeout.connect(self.next_frame)self.timer.start(33)def next_frame(self):# 读取视频流ret, frame = self.video_capture.read()# 转换为RGB格式rgb_frame = frame[:, :, ::-1]# 检测人脸face_locations = face_recognition.face_locations(rgb_frame)face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)# 对比已知人脸for face_encoding in face_encodings:found = Falsefor person_name, known_face_encodings in self.known_faces.items():matches = face_recognition.compare_faces(known_face_encodings, face_encoding, tolerance=0.4)if True in matches:cv2.putText(frame, f" {person_name}!", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)found = Truebreakif found:break# 将视频帧显示在标签中height, width, channel = frame.shapebytesPerLine = 3 * widthqImg = QImage(frame.data, width, height, bytesPerLine, QImage.Format_RGB888)pixmap = QPixmap.fromImage(qImg)self.label.setPixmap(pixmap)def toggle_video(self):if self.timer.isActive():self.timer.stop()else:self.timer.start(33)if __name__ == '__main__':app = QApplication(sys.argv)player = VideoPlayer()player.show()sys.exit(app.exec_())