【人机交互】pyqt5+opencv对人脸进行识别

【人机交互】pyqt5+opencv对人脸进行识别,第1张

解决问题:通过pyqt5对opencv人脸识别模块进行调用

文章目录
  • 1. pyqt5界面的设计
  • 2. 建立一个主函数调用pyqt界面
  • 3.大功告成!
  • 4. 项目链接

1. pyqt5界面的设计

其中按钮设计如下:

*** 作方法参考:https://www.cnblogs.com/wojianxin/p/12629085.html

2. 建立一个主函数调用pyqt界面
#-*- codeing = utf-8 -*-
#@Function: 
#@Time : 2022/4/7 22:20
#@Author : yx
#@File : main.py
#@Software : PyCharm

import sys
import cv2 as cv

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QFileDialog, QMainWindow
from PyQt5.QtCore import QTimer,QDateTime

from Project import Ui_MainWindow

class PyQtMainEntry(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.camera = cv.VideoCapture(0)
        self.is_camera_opened = False  # 摄像头有没有打开标记

        # 定时器:30ms捕获一帧
        self._timer = QtCore.QTimer(self)
        self._timer.timeout.connect(self._queryFrame)
        self._timer.setInterval(30)     # 修改帧差

        # 时间
        self.statusShowTime()

    # 显示时间
    def showCurrentTime(self, timeLabel):
        # 获取系统当前时间
        time = QDateTime.currentDateTime()
        # 设置系统时间的显示格式
        self.timeDisplay = time.toString('yyyy-MM-dd hh:mm:ss dddd')
        # 状态栏显示
        timeLabel.setText(self.timeDisplay)

    def statusShowTime(self):
        self.timer = QTimer()
        # self.statusbar.addPermanentWidget(self.TimeLabel, 0)   # 显示在右下角
        self.timer.timeout.connect(lambda: self.showCurrentTime(self.TimeLabel))  # 这个通过调用槽函数来刷新时间
        self.timer.start(1000)  # 每隔一秒刷新一次,这里设置为1000ms  即1s

    def btnReadImage_Clicked(self):
        '''
        从本地读取图片
        '''
        # 打开文件选取对话框
        self.filename,  _ = QFileDialog.getOpenFileName(self, '打开')
        self.filename = str(self.filename)

        if self.filename:
            self.capturedImg = cv.imread(self.filename)
            # OpenCV图像以BGR通道存储,显示时需要从BGR转到RGB
            self.captured = cv.cvtColor(self.capturedImg, cv.COLOR_BGR2RGB)

            rows, cols, channels = self.captured.shape
            bytesPerLine = channels * cols
            QImg = QImage(self.captured.data, cols, rows, bytesPerLine, QImage.Format_RGB888)
            self.Videolabel.setPixmap(QPixmap.fromImage(QImg).scaled(
            self.Videolabel.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
            self.Videolabel.setScaledContents(True)


    def btnOpenCamera_Clicked(self):
        '''
        打开和关闭摄像头
        '''
        self.is_camera_opened = ~self.is_camera_opened
        if self.is_camera_opened:
            self.btnShowCamera.setText("关闭摄像头")
            self._timer.start()
        else:
            self.btnShowCamera.setText("打开摄像头")
            self._timer.stop()


    def _queryFrame(self):
        '''
        循环捕获图片
        '''
        ret, self.frame = self.camera.read()

        img_rows, img_cols, channels = self.frame.shape
        bytesPerLine = channels * img_cols

        cv.cvtColor(self.frame, cv.COLOR_BGR2RGB, self.frame)
        QImg = QImage(self.frame.data, img_cols, img_rows, bytesPerLine, QImage.Format_RGB888)
        self.Videolabel.setPixmap(QPixmap.fromImage(QImg).scaled(
        self.Videolabel.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
        self.Videolabel.setScaledContents(True)

    # opencv人脸识别
    def face_detect(self, img_path, CADES_PATH):
        color = (0, 0, 255)
        img_bgr = cv.imread(img_path)
        classifier = cv.CascadeClassifier(CADES_PATH)
        img_gray = cv.cvtColor(img_bgr, cv.COLOR_BGR2GRAY)
        facerects = classifier.detectMultiScale(img_gray)
        for rect in facerects:
            x, y, w, h = rect
            cv.rectangle(img_bgr, (x, y), (x + w, y + h), color, 2)
        return img_bgr

    def btnOpenXml_Clicked(self):
        self.path_Xmlfilename,  _ = QFileDialog.getOpenFileName(self, '获取.xml文件')
        self.path_Xmlfilename = str(self.path_Xmlfilename)

    def btnStartLabel_Clicked(self):
        '''
        开始标记
        '''
        # 摄像头未打开,执行读取图片
        if not self.is_camera_opened:
            # 获取图像
            self.capturedImage = self.filename
        else:
            self.capturedImage = self.frame
            self.capturedImage = cv.cvtColor(self.capturedImage, cv.COLOR_RGB2BGR)
            cv.imwrite('./videoImg.jpg', self.capturedImage)
            self.capturedImage = './videoImg.jpg'

        self.imgInfer = self.face_detect(self.capturedImage, self.path_Xmlfilename)

        self.imgInfer = cv.cvtColor(self.imgInfer, cv.COLOR_BGR2RGB)

        rows, cols, channels = self.imgInfer.shape
        bytesPerLine = channels * cols
        # Qt显示图片时,需要先转换成QImgage类型
        QImg = QImage(self.imgInfer.data, cols, rows, bytesPerLine, QImage.Format_RGB888)
        self.DetectImagelabel.setPixmap(QPixmap.fromImage(QImg).scaled(
        self.DetectImagelabel.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
        self.DetectImagelabel.setScaledContents(True)

    def btnSaveResult_Clicked(self):
        path_filename = QFileDialog.getExistingDirectory(self, '结果保存')
        if path_filename:
            self.saveImage = cv.cvtColor(self.imgInfer, cv.COLOR_RGB2BGR)
            cv.imwrite(path_filename + '/' + self.timeDisplay[:10]
                        + '_' + str(10) + '.jpg', self.saveImage)
        self.PathLineEdit.setText(path_filename)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = PyQtMainEntry()
    window.show()
    sys.exit(app.exec_())
3.大功告成!


其中.xml文件在anaconda文件夹下:
D:\AI\anaconda\anaconda3\envs\TargetD\Lib\site-packages\opencv_python-4.5.5.64-py3.7-win-amd64.egg\cv2\data

4. 项目链接

项目链接:https://download.csdn.net/download/qq_44747572/85170428

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/719102.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-25
下一篇 2022-04-25

发表评论

登录后才能评论

评论列表(0条)

保存