文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Python PyQt5 人脸识别软件

2023-08-31 22:11

关注

在这里插入图片描述

# !/usr/bin/python3# -*- coding:utf-8 -*-"""@author: JHC000abc@gmail.com@file: untitled_ctrl.py@time: 2023/8/6 16:29@desc:"""import copyimport threadingimport timeimport tracebackimport uuidimport osimport cv2from gui.ui.untitled import Ui_widgetfrom PyQt5 import QtWidgetsfrom PyQt5.QtCore import pyqtSignalfrom PyQt5.QtGui import QPixmap, QImagefrom threading import Threadfrom queue import Queueimport numpyimport PyQt5class UntitledCtrl(QtWidgets.QWidget):    """    """    single_frame = pyqtSignal(PyQt5.QtGui.QImage)    def __init__(self, rootpath):        super(UntitledCtrl, self).__init__()        self.rootpath = rootpath        self.resize(980, 521)        self.ui = Ui_widget()        self.ui.setupUi(self)        print(rootpath)        self.img_que = Queue()        self.ui.pushButton_cut.hide()        self._flag()        self._slot()        self._thread()    def _thread(self):        t = Thread(target=self.camera)        t.start()        t2 = Thread(target=self.show_img)        t2.start()    def _flag(self):        self.flag_start = True        self.flag_face = True        self.cap = None        self.pause = False        self.frame = ""        self.cut = ""    def _slot(self):        self.ui.pushButton_start.clicked.connect(self.start_pause)        self.ui.pushButton_check_face.clicked.connect(self.face_check)        self.single_frame.connect(self.th_show)    def th_show(self, img):        if img:            try:                self.ui.label_camera.setPixmap(QPixmap(img))            except BaseException:                pass    def show_img(self):        """        :return:        """        while True:            try:                if not self.img_que.empty():                    img, nums = self.img_que.get()                    for i in range(nums):                        self.single_frame.emit(img)                        time.sleep(0.01)            except Exception as e:                print("e2", e)                time.sleep(0.01)    def add_face_box(self):        """        :return:        """        flag = False        if self.flag_start:            if self.frame is not None:                self.cut = copy.deepcopy(self.frame)                try:                    if self.flag_face:                        for x, y, w, h in self.get_face_opt():try:    self.cut = cv2.rectangle(        img=self.cut,        pt1=(x, y),        pt2=(x + w, y + h),        color=(0, 0, 255),        thickness=2,        lineType=cv2.INTER_LINEAR,    )    flag = Trueexcept BaseException:    pass                    image = cv2.cvtColor(self.cut, cv2.COLOR_RGB2BGR)                    self.cut = QImage(                        image.data,                        image.shape[1],                        image.shape[0],                        QImage.Format_RGB888)                    if flag:                        self.img_que.put([self.cut, 30])                    else:                        self.img_que.put([self.cut, 1])                except Exception as e:                    print("e1", str(traceback.print_exc()))    def camera(self):        """        :return:        """        try:            if not self.cap:                self.cap = cv2.VideoCapture(0)  # 使用默认摄像头            if not self.cap.isOpened():                print("无法打开摄像头")                exit()            while not self.pause:                ret, self.frame = self.cap.read()                if not ret:                    print("无法读取视频流")                    break                else:                    self.add_face_box()            self.cap.release()        except Exception as e:            print(traceback.print_exc())    def get_face_opt(self):        """        :return:        """        face_cascade = cv2.CascadeClassifier(            cv2.data.haarcascades +            'haarcascade_frontalface_default.xml')        try:            faces = face_cascade.detectMultiScale(self.cut, 1.1, 4)            for (x, y, w, h) in faces:                yield x, y, w, h        except BaseException:            pass    def start_pause(self):        """        :return:        """        if self.flag_start:            self.ui.pushButton_start.setText("暂停")            self.flag_start = False        else:            self.ui.pushButton_start.setText("开始")            self.flag_start = True    def face_check(self):        """        :return:        """        if self.flag_face:            self.flag_face = False            self.ui.pushButton_check_face.setText("暂停识别")        else:            self.flag_face = True            self.ui.pushButton_check_face.setText("识别人脸")    def save(self):        file = "gui/res/{}.png".format(uuid.uuid4())        cv2.imencode(            ".{}".format(".{}".format(os.path.splitext(file)[-1])), self.frame)[1].tofile(file)
# -*- coding: utf-8 -*-# Form implementation generated from reading ui file 'untitled.ui'## Created by: PyQt5 UI code generator 5.15.9## WARNING: Any manual changes made to this file will be lost when pyuic5 is# run again.  Do not edit this file unless you know what you are doing.from PyQt5 import QtCore, QtGui, QtWidgetsclass Ui_widget(object):    def setupUi(self, widget):        widget.setObjectName("widget")        # widget.resize(836, 521)        self.horizontalLayout = QtWidgets.QHBoxLayout(widget)        self.horizontalLayout.setObjectName("horizontalLayout")        self.stackedWidget = QtWidgets.QStackedWidget(widget)        self.stackedWidget.setObjectName("stackedWidget")        self.page = QtWidgets.QWidget()        self.page.setObjectName("page")        self.gridLayout = QtWidgets.QGridLayout(self.page)        self.gridLayout.setObjectName("gridLayout")        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()        self.horizontalLayout_2.setObjectName("horizontalLayout_2")        self.label_camera = QtWidgets.QLabel(self.page)        self.label_camera.setStyleSheet("border-width: 3px;\n""border-style: dot-dot-dash;\n""border-color: purple;\n""border-radius: 50px;\n""")        self.label_camera.setText("")        self.label_camera.setObjectName("label_camera")        self.horizontalLayout_2.addWidget(self.label_camera)        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)        self.horizontalLayout_2.addItem(spacerItem)        self.frame = QtWidgets.QFrame(self.page)        self.frame.setStyleSheet("border-width: 3px;\n""border-style: dot-dot-dash;\n""border-color: purple;\n""border-radius: 50px;\n""")        self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)        self.frame.setFrameShadow(QtWidgets.QFrame.Raised)        self.frame.setObjectName("frame")        self.pushButton_start = QtWidgets.QPushButton(self.frame)        self.pushButton_start.setGeometry(QtCore.QRect(100, 20, 93, 28))        self.pushButton_start.setStyleSheet("border-style: solid;\n""border-color:purple;")        self.pushButton_start.setObjectName("pushButton_start")        self.pushButton_cut = QtWidgets.QPushButton(self.frame)        self.pushButton_cut.setGeometry(QtCore.QRect(100, 80, 93, 28))        self.pushButton_cut.setStyleSheet("border-style: solid;\n""border-color:purple;")        self.pushButton_cut.setObjectName("pushButton_cut")        self.pushButton_check_face = QtWidgets.QPushButton(self.frame)        self.pushButton_check_face.setGeometry(QtCore.QRect(100, 140, 93, 28))        self.pushButton_check_face.setStyleSheet("border-style: solid;\n""border-color:purple;")        self.pushButton_check_face.setObjectName("pushButton_check_face")        self.horizontalLayout_2.addWidget(self.frame)        self.horizontalLayout_2.setStretch(0, 150)        self.horizontalLayout_2.setStretch(1, 1)        self.horizontalLayout_2.setStretch(2, 100)        self.gridLayout.addLayout(self.horizontalLayout_2, 0, 0, 1, 1)        self.stackedWidget.addWidget(self.page)        self.page_2 = QtWidgets.QWidget()        self.page_2.setObjectName("page_2")        self.stackedWidget.addWidget(self.page_2)        self.horizontalLayout.addWidget(self.stackedWidget)        self.retranslateUi(widget)        QtCore.QMetaObject.connectSlotsByName(widget)    def retranslateUi(self, widget):        _translate = QtCore.QCoreApplication.translate        widget.setWindowTitle(_translate("widget", "FaceCheck"))        self.pushButton_start.setText(_translate("widget", "启动"))        self.pushButton_cut.setText(_translate("widget", "截图"))        self.pushButton_check_face.setText(_translate("widget", "识别人脸"))
# !/usr/bin/python3# -*- coding:utf-8 -*-"""@author: JHC000abc@gmail.com@file: main.py@time: 2023/8/6 16:31@desc: """from gui.ctrl.untitled_ctrl import UntitledCtrlimport osimport sysfrom PyQt5 import QtWidgetsfrom PyQt5.QtCore import QCoreApplication, Qtfrom qt_material import apply_stylesheetif __name__ == "__main__":    root_path = os.getcwd()    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)    app = QtWidgets.QApplication(sys.path)    try:        apply_stylesheet(app, theme="dark_teal.xml")    except BaseException:        print("样式加载失败")    Form = UntitledCtrl(root_path)    Form.show()    sys.exit(app.exec_())

haarcascade_frontalface_default.xml
密码:JDBC

2

来源地址:https://blog.csdn.net/CXY00000/article/details/132137633

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯