Python教程

python关于PyQt5结合opencv的简单使用

本文主要是介绍python关于PyQt5结合opencv的简单使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一、话不多说,先看图

借用一下马先生的图()

二、看main函数

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main_window = QMainWindow()

    ui = boke_ui.Ui_MainWindow()
    ui.setupUi(main_window)
    main_window.show()
    my_face = Campus_face(ui)
    sys.exit(app.exec())

main函数也没什么

三、我写的类

class Campus_face:
    img_label = None
    face_label = None
    car_label = None
    classroom_img = None
    face_collection = 0

    def __init__(self, my_ui):
        self.my_ui = my_ui
        self.set_face_label()

        my_ui.pushButton.clicked.connect(self.face_reg_thread)
        my_ui.pushButton_2.clicked.connect(self.face_face_collection_yz)

    def set_face_label(self):
        hbox = QHBoxLayout(self.my_ui.groupBox)
        self.img_label = QLabel()
        hbox.addWidget(self.img_label)

        hbox2 = QHBoxLayout(self.my_ui.groupBox_2)
        self.face_label = QLabel()
        hbox2.addWidget(self.face_label)

        hbox3 = QHBoxLayout(self.my_ui.groupBox_3)
        self.car_label = QLabel()
        hbox3.addWidget(self.car_label)

    def face_face_collection_yz(self):
        self.face_collection = 1

    def face_reg_thread(self):
        th = threading.Thread(target=self.face_reg)
        th.start()

    def face_reg(self):
        self.face_collection = 0
        cap = cv2.VideoCapture(1)
        frame_num = cap.get(propId=cv2.CAP_PROP_FPS)  # 获取视频帧数

        frame_fourcc = cap.get(propId=cv2.CAP_PROP_FOURCC)  # 视频编码格式
        frame_count = cap.get(propId=cv2.CAP_PROP_FRAME_COUNT)  # 视频有多少帧
        frame_height = cap.get(propId=cv2.CAP_PROP_FRAME_HEIGHT)  # 视频 高
        frame_width = cap.get(propId=cv2.CAP_PROP_FRAME_WIDTH)  # 视频  宽

        while cap.isOpened():
            flag, frame = cap.read()
            frame = cv2.resize(src=frame, dsize=(int(frame_width / 1.2), int(frame_height / 1.2)), interpolation=None)
            frame = cv2.flip(frame, 1)
            img = frame
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            faces = face_cascade.detectMultiScale(frame, scaleFactor=1.2, minNeighbors=5, flags=None, minSize=None,
                                                  maxSize=None)

            for (x, y, w, h) in faces:
                # 人脸检测
                img = cv2.rectangle(img=img, pt1=(x, y), pt2=(x + w, y + h),
                                    color=[int(np.random.randint(0, 256, size=1)[0]),
                                           int(np.random.randint(0, 256, size=1)[0]),
                                           int(np.random.randint(0, 256, size=1)[0])], thickness=2)

                face_area = img[y:y + h, x:x + w]
                img_face_name = r'.\tmp\tmp_face_img.jpg'
                cv2.imwrite(img_face_name, face_area)
                self.face_label.setPixmap(QPixmap(img_face_name))

                # 人眼
                eyes = eye_cascade.detectMultiScale(face_area, scaleFactor=1.2, minNeighbors=2, flags=None,
                                                    minSize=None, maxSize=None)
                for (ex, ey, ew, eh) in eyes:
                    cv2.rectangle(face_area, (ex, ey), (ex + ew, ey + eh),
                                  color=[int(np.random.randint(0, 256, size=1)[0]),
                                         int(np.random.randint(0, 256, size=1)[0]),
                                         int(np.random.randint(0, 256, size=1)[0])], thickness=1, lineType=None,
                                  shift=None)

            # cv2.imshow('campus face', img)
            img_name = r'.\tmp\tmp_img.jpg'
            cv2.imwrite(img_name, img)
            self.img_label.setPixmap(QPixmap(img_name))


            if ord('q') == cv2.waitKey(int(1000 / frame_num)) or flag == False:
                break
            if self.face_collection == 1:
                break
        cv2.destroyAllWindows()
        cap.release()

内容也不算多,知识挺多的

四、当然还得引入一些模块及相关配置

import sys

import cv2
import numpy as np
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QHBoxLayout, QLabel, QVBoxLayout, QApplication, QMainWindow, QFormLayout, QLineEdit, QWidget
import threading
from Campus_security import boke_ui

face_cascade = cv2.CascadeClassifier(
    r'G:\huwei_welding\Campus_security\cascade_file\haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(r'G:\huwei_welding\Campus_security\cascade_file\haarcascade_eye.xml')

下面两个是人脸和人眼的级联器而已

五、还有图形界面

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'boke_ui.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# 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, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1148, 724)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
        font = QtGui.QFont()
        font.setFamily("黑体")
        font.setPointSize(14)
        self.tabWidget.setFont(font)
        self.tabWidget.setObjectName("tabWidget")
        self.tab = QtWidgets.QWidget()
        self.tab.setObjectName("tab")
        self.pushButton = QtWidgets.QPushButton(self.tab)
        self.pushButton.setGeometry(QtCore.QRect(280, 560, 171, 61))
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self.tab)
        self.pushButton_2.setGeometry(QtCore.QRect(60, 560, 181, 61))
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_5 = QtWidgets.QPushButton(self.tab)
        self.pushButton_5.setGeometry(QtCore.QRect(490, 560, 171, 61))
        self.pushButton_5.setObjectName("pushButton_5")
        self.widget = QtWidgets.QWidget(self.tab)
        self.widget.setGeometry(QtCore.QRect(10, 10, 1101, 541))
        self.widget.setObjectName("widget")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.widget)
        self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.groupBox = QtWidgets.QGroupBox(self.widget)
        self.groupBox.setObjectName("groupBox")
        self.horizontalLayout_2.addWidget(self.groupBox)
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.groupBox_2 = QtWidgets.QGroupBox(self.widget)
        self.groupBox_2.setStyleSheet("")
        self.groupBox_2.setObjectName("groupBox_2")
        self.verticalLayout.addWidget(self.groupBox_2)
        self.groupBox_3 = QtWidgets.QGroupBox(self.widget)
        self.groupBox_3.setObjectName("groupBox_3")
        self.verticalLayout.addWidget(self.groupBox_3)
        self.horizontalLayout_2.addLayout(self.verticalLayout)
        self.horizontalLayout_2.setStretch(0, 4)
        self.horizontalLayout_2.setStretch(1, 2)
        self.tabWidget.addTab(self.tab, "")
        self.tab_2 = QtWidgets.QWidget()
        self.tab_2.setObjectName("tab_2")
        self.tabWidget.addTab(self.tab_2, "")
        self.horizontalLayout.addWidget(self.tabWidget)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1148, 26))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "关于PyQt图像化界面人脸识别"))
        self.pushButton.setText(_translate("MainWindow", "打开摄像头"))
        self.pushButton_2.setText(_translate("MainWindow", "关闭摄像头"))
        self.pushButton_5.setText(_translate("MainWindow", "保存视频"))
        self.groupBox.setTitle(_translate("MainWindow", "视频"))
        self.groupBox_2.setTitle(_translate("MainWindow", "人脸"))
        self.groupBox_3.setTitle(_translate("MainWindow", "车辆"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "QT视频处理"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "百度云语音识别"))

Qt Designer拖出来的,没什么好讲的

六、运行

将二、三、四方一个文件,五放一个文件(这命名和我的不同那就得修改模块引入那句代码了),然后就可以运行了

七、关键代码关键知识点

face_cascade = cv2.CascadeClassifier(
    r'G:\huwei_welding\Campus_security\cascade_file\haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(r'G:\huwei_welding\Campus_security\cascade_file\haarcascade_eye.xml')

这个没有,github opencv自己下载  (级联器相关)

    def set_face_label(self):
        hbox = QHBoxLayout(self.my_ui.groupBox)
        self.img_label = QLabel()
        hbox.addWidget(self.img_label)

        hbox2 = QHBoxLayout(self.my_ui.groupBox_2)
        self.face_label = QLabel()
        hbox2.addWidget(self.face_label)

        hbox3 = QHBoxLayout(self.my_ui.groupBox_3)
        self.car_label = QLabel()
        hbox3.addWidget(self.car_label)

在groupbox那添加label,用于显示图片而已

faces = face_cascade.detectMultiScale(frame, scaleFactor=1.2, minNeighbors=5, flags=None, minSize=None,
                                      maxSize=None)

for (x, y, w, h) in faces:
    # 人脸检测
    img = cv2.rectangle(img=img, pt1=(x, y), pt2=(x + w, y + h),
                        color=[int(np.random.randint(0, 256, size=1)[0]),
                               int(np.random.randint(0, 256, size=1)[0]),
                               int(np.random.randint(0, 256, size=1)[0])], thickness=2)

    face_area = img[y:y + h, x:x + w]
    img_face_name = r'.\tmp\tmp_face_img.jpg'
    cv2.imwrite(img_face_name, face_area)
    self.face_label.setPixmap(QPixmap(img_face_name))

这个也就是将人脸框出来而已(级联器搞出来的人脸区域坐标),然后花里胡哨点用numpy的随机数生成好看点的框框而已

八、好像也没有什么了

忘了再回去复习下吧,后面在不错人脸识别(人脸训练)

 

这篇关于python关于PyQt5结合opencv的简单使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!