为了很进一步的接近项目,我用pyqtf进行项目的封状,方便以后管理。
1、安装pyqt5
forlinx@ok3588:~$ sudo apt install python3-pyqt5
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
libqt5designer5 libqt5help5 python3-sip
Suggested packages:
python3-pyqt5-dbg
The following NEW packages will be installed:
libqt5designer5 libqt5help5 python3-pyqt5 python3-sip
0 upgraded, 4 newly installed, 0 to remove and 3 not upgraded.
Need to get 5043 kB of archives.
After this operation, 22.9 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://mirrors.163.com/ubuntu-ports focal/universe arm64 libqt5designer5 arm64 5.12.8-0ubuntu1 [2721 kB]
Get:2 http://mirrors.163.com/ubuntu-ports focal/universe arm64 libqt5help5 arm64 5.12.8-0ubuntu1 [125 kB]
Get:3 http://mirrors.163.com/ubuntu-ports focal/universe arm64 python3-sip arm64 4.19.21+dfsg-1build1 [85.7 kB]
Get:4 http://mirrors.163.com/ubuntu-ports focal/universe arm64 python3-pyqt5 arm64 5.14.1+dfsg-3build1 [2112 kB]
Fetched 5043 kB in 1min 1s (82.3 kB/s)
Selecting previously unselected package libqt5designer5:arm64.
(Reading database ... 58475 files and directories currently installed.)
Preparing to unpack .../libqt5designer5_5.12.8-0ubuntu1_arm64.deb ...
Unpacking libqt5designer5:arm64 (5.12.8-0ubuntu1) ...
Selecting previously unselected package libqt5help5:arm64.
Preparing to unpack .../libqt5help5_5.12.8-0ubuntu1_arm64.deb ...
Unpacking libqt5help5:arm64 (5.12.8-0ubuntu1) ...
Selecting previously unselected package python3-sip.
Preparing to unpack .../python3-sip_4.19.21+dfsg-1build1_arm64.deb ...
Unpacking python3-sip (4.19.21+dfsg-1build1) ...
Selecting previously unselected package python3-pyqt5.
Preparing to unpack .../python3-pyqt5_5.14.1+dfsg-3build1_arm64.deb ...
Unpacking python3-pyqt5 (5.14.1+dfsg-3build1) ...
Setting up libqt5designer5:arm64 (5.12.8-0ubuntu1) ...
Setting up libqt5help5:arm64 (5.12.8-0ubuntu1) ...
Setting up python3-sip (4.19.21+dfsg-1build1) ...
Setting up python3-pyqt5 (5.14.1+dfsg-3build1) ...
Processing triggers for libc-bin (2.31-0ubuntu9) ...
/sbin/ldconfig.real: /lib/aarch64-linux-gnu/libvirtualkeyboard.so.1 is not a symbolic link
检查是否安装成功:
forlinx@ok3588:~$ python3
Python 3.8.2 (default, Mar 13 2020, 10:14:16)
[GCC 9.2.1 20200306] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import PyQt5
>>> quit()
代码:
import sys
import os
import cv2
import numpy as np
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import QPalette, QBrush, QPixmap
face_detection_model = "../models/yunet.onnx"
face_recognition_model = "../models/face_recognizer_fast.onnx"
images_path = "../images"
faceDetector = cv2.FaceDetectorYN.create(face_detection_model, "", input_size=(640, 480))
recognizer = cv2.FaceRecognizerSF.create(face_recognition_model, "")
cosine_similarity_threshold = 0.363
l2_similarity_threshold = 1.128
def Gets_Facial_Features(images_path):
images_feature_list = []
ID_list = []
for image_name in os.listdir(images_path):
ID_list.append(image_name.split('.')[0])
image = cv2.imread(images_path + '/' + image_name)
faces1 = faceDetector.detect(image)
aligned_face1 = recognizer.alignCrop(image, faces1[1][0])
image_feature = recognizer.feature(aligned_face1)
images_feature_list.append(image_feature)
return ID_list, images_feature_list
class Ui_MainWindow(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Ui_MainWindow, self).__init__(parent)
self.CAM_NUM = 74
self.label_show_camera = None
self.label_move = None
self.button_close = None
self.button_open_camera = None
self.__layout_data_show = None
self.__layout_fun_button = None
self.__layout_main = None
self.image = None
self.timer_camera = QtCore.QTimer()
self.cap = cv2.VideoCapture(self.CAM_NUM)
self.cap.set(3, 640)
self.cap.set(4, 480)
self.ID_list, self.images_feature_list = Gets_Facial_Features(images_path)
self.set_ui()
self.slot_init()
self.__flag_work = 0
self.x = 0
self.count = 0
def set_ui(self):
self.__layout_main = QtWidgets.QHBoxLayout()
self.__layout_fun_button = QtWidgets.QHBoxLayout()
self.__layout_data_show = QtWidgets.QVBoxLayout
self.button_open_camera = QtWidgets.QPushButton(u'打开相机')
self.button_close = QtWidgets.QPushButton(u'退出')
button_color = [self.button_open_camera, self.button_close]
for i in range(2):
button_color[i].setStyleSheet("QPushButton{color:black}"
"QPushButton:hover{color:red}"
"QPushButton{background-color:rgb(78,255,255)}"
"QpushButton{border:2px}"
"QPushButton{border_radius:10px}"
"QPushButton{padding:2px 4px}")
self.button_open_camera.setMinimumHeight(50)
self.button_close.setMinimumHeight(50)
self.move(500, 500)
self.label_show_camera = QtWidgets.QLabel()
self.label_move = QtWidgets.QLabel()
self.label_move.setFixedSize(100, 100)
self.label_show_camera.setFixedSize(641, 481)
self.label_show_camera.setAutoFillBackground(False)
self.__layout_fun_button.addWidget(self.button_open_camera)
self.__layout_fun_button.addWidget(self.button_close)
self.__layout_fun_button.addWidget(self.label_move)
self.__layout_main.addLayout(self.__layout_fun_button)
self.__layout_main.addWidget(self.label_show_camera)
self.setLayout(self.__layout_main)
self.label_move.raise_()
self.setWindowTitle(u"摄像头")
"""
# 设置背景颜色
palettel1 = QPalette()
palettel1.setBrush(self.backgroundRole(), QBrush(QPixmap('background.jpg')))
self.setPalette(palettel1)
"""
def slot_init(self):
self.button_open_camera.clicked.connect(self.button_open_camera_click)
self.timer_camera.timeout.connect(self.show_camera)
self.button_close.clicked.connect(self.close)
def button_open_camera_click(self):
if not self.timer_camera.isActive():
flag = self.cap.open(self.CAM_NUM)
if not flag:
msg = QtWidgets.QMessageBox.Warning(self, u"Warning", u"请检测相与电脑是否连接正确",
buttons=QtWidgets.QMessageBox.Ok,
defaultButton=QtWidgets.QMessageBox.Ok)
else:
self.timer_camera.start(30)
self.button_open_camera.setText(u"关闭相机")
else:
self.timer_camera.stop()
self.cap.release()
self.label_show_camera.clear()
self.button_open_camera.setText(u'打开相机')
def show_camera(self):
flag, show = self.cap.read()
if flag is not True:
print('摄像头未打开')
else:
frame_faces = faceDetector.detect(show)
if frame_faces[1] is not None:
for idx, face in enumerate(frame_faces[1]):
coords = face[:-1].astype(np.int32)
cv2.rectangle(show, (coords[0], coords[1]), (coords[0] + coords[2], coords[1] + coords[3]), (255, 0, 0), thickness=2)
aligned_face = recognizer.alignCrop(show, frame_faces[1][idx])
frame_feature = recognizer.feature(aligned_face)
for index, image_feature in enumerate(self.images_feature_list):
cosine_score = recognizer.match(frame_feature, image_feature, 0)
l2_score = recognizer.match(frame_feature, image_feature, 1)
if cosine_score >= cosine_similarity_threshold:
cv2.putText(show, self.ID_list[index], (coords[0] + 5, coords[1] - 5), cv2.FONT_HERSHEY_SIMPLEX, 1,
(0, 255, 0), 2)
i = 1
elif l2_score <= l2_similarity_threshold:
cv2.putText(show, self.ID_list[index], (coords[0] + 5, coords[1] - 5), cv2.FONT_HERSHEY_SIMPLEX, 1,
(0, 255, 0), 2)
i = 1
showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0], QtGui.QImage.Format_RGB888)
self.label_show_camera.setPixmap(QtGui.QPixmap.fromImage(showImage))
def closeEvent(self, event):
print(u"关闭")
ok = QtWidgets.QPushButton()
cancel = QtWidgets.QPushButton()
msg = QtWidgets.QMessageBox(QtWidgets.QMessageBox, u"关闭", u"是否关闭")
msg.addButton(ok, QtWidgets.QMessageBox.ActionRole)
msg.addButton(cancel, QtWidgets.QMessageBox.RejectRole)
ok.setText(u"确定")
cancel.setText(u"取消")
if msg.exec_() == QtWidgets.QMessageBox.RejectRole:
event.ignore()
else:
if self.cap.isOpened():
self.cap.release()
if self.timer_camera.isActive():
self.timer_camera.stop()
event.accept()
if __name__ == '__main__':
App = QApplication(sys.argv)
win = Ui_MainWindow()
win.show()
sys.exit(App.exec_())
实测效果