24、Pyqt 打开视频,关闭视频及眨眼睛次数统计

基本思想:使用pyqt 开发一个打开摄像头和关闭摄像头,同时加入了人眼睛眨的次数统计;

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import cv2

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import QPalette, QBrush, QPixmap
import os
import dlib
from scipy.spatial import distance
import os
from imutils import face_utils


class Ui_MainWindow(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Ui_MainWindow, self).__init__(parent)

        # self.face_recong = face.Recognition()
        self.timer_camera = QtCore.QTimer()
        self.cap = cv2.VideoCapture()
        self.CAM_NUM = 0
        self.set_ui()
        self.slot_init()
        self.__flag_work = 0
        self.x = 0
        self.count = 0
        self.shape_detector_path = 'shape_predictor_68_face_landmarks.dat'  # 人脸特征点检测模型路径

        self.detector = dlib.get_frontal_face_detector()  # 人脸检测器
        self.predictor = dlib.shape_predictor(self.shape_detector_path)  # 人脸特征点检测器
        self.EYE_AR_THRESH = 0.3  # EAR阈值
        self.EYE_AR_CONSEC_FRAMES = 3  # 当EAR小于阈值时,接连多少帧一定发生眨眼动作

        # 对应特征点的序号
        self.RIGHT_EYE_START = 37 - 1
        self.RIGHT_EYE_END = 42 - 1
        self.LEFT_EYE_START = 43 - 1
        self.LEFT_EYE_END = 48 - 1
        self.face =True


    def set_ui(self):

        self.__layout_main = QtWidgets.QHBoxLayout()
        self.__layout_fun_button = QtWidgets.QVBoxLayout()
        self.__layout_data_show = QtWidgets.QVBoxLayout()

        self.button_open_camera = QtWidgets.QPushButton(u'开始播放')

        self.button_close = QtWidgets.QPushButton(u'关闭播放')

        # Button 的颜色修改
        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)

        # move()方法移动窗口在屏幕上的位置到x = 300,y = 300坐标。
        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'摄像头')

        '''
        # 设置背景图片
        palette1 = QPalette()
        palette1.setBrush(self.backgroundRole(), QBrush(QPixmap('background.png')))
        self.setPalette(palette1)
        '''

    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 self.timer_camera.isActive() == False:
            self.frame_counter = 0  # 连续帧计数
            self.blink_counter = 0  # 眨眼计数
            flag = self.cap.open(self.CAM_NUM)
            if flag == False:
                msg = QtWidgets.QMessageBox.warning(self, u"Warning", u"请检测相机与电脑是否连接正确",
                                                    buttons=QtWidgets.QMessageBox.Ok,
                                                    defaultButton=QtWidgets.QMessageBox.Ok)
            # if msg==QtGui.QMessageBox.Cancel:
            #                     pass
            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, self.image = self.cap.read()
        # face = self.face_detect.align(self.image)
        if self.face:
             self.detect_eyes()
        self.show = cv2.resize(self.image, (640, 480))
        self.show = cv2.cvtColor(self.show, cv2.COLOR_BGR2RGB)
        # print(show.shape[1], show.shape[0])
        # show.shape[1] = 640, show.shape[0] = 480
        showImage = QtGui.QImage(self.show.data, self.show.shape[1], self.show.shape[0], QtGui.QImage.Format_RGB888)
        self.label_show_camera.setPixmap(QtGui.QPixmap.fromImage(showImage))
        # self.x += 1
        # self.label_move.move(self.x,100)

        # if self.x ==320:
        #     self.label_show_camera.raise_()

    def closeEvent(self, event):

        ok = QtWidgets.QPushButton()
        cacel = QtWidgets.QPushButton()

        msg = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, u"关闭", u"是否关闭!")

        msg.addButton(ok, QtWidgets.QMessageBox.ActionRole)
        msg.addButton(cacel, QtWidgets.QMessageBox.RejectRole)
        ok.setText(u'确定')
        cacel.setText(u'取消')
        # msg.setDetailedText('sdfsdff')
        if msg.exec_() == QtWidgets.QMessageBox.RejectRole:
            event.ignore()
        else:
            #             self.socket_client.send_command(self.socket_client.current_user_command)
            if self.cap.isOpened():
                self.cap.release()
            if self.timer_camera.isActive():
                self.timer_camera.stop()
            event.accept()

    def detect_eyes(self):
        gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
        rects = self.detector(gray, 0)  # 人脸检测
        for rect in rects:  # 遍历每一个人脸
            print('-' * 20)
            shape = self.predictor(gray, rect)  # 检测特征点
            points = face_utils.shape_to_np(shape)  # convert the facial landmark (x, y)-coordinates to a NumPy array
            leftEye = points[self.LEFT_EYE_START:self.LEFT_EYE_END + 1]  # 取出左眼对应的特征点
            rightEye = points[self.RIGHT_EYE_START:self.RIGHT_EYE_END + 1]  # 取出右眼对应的特征点
            leftEAR = self.eye_aspect_ratio(leftEye)  # 计算左眼EAR
            rightEAR = self.eye_aspect_ratio(rightEye)  # 计算右眼EAR
            print('leftEAR = {0}'.format(leftEAR))
            print('rightEAR = {0}'.format(rightEAR))

            ear = (leftEAR + rightEAR) / 2.0  # 求左右眼EAR的均值

            leftEyeHull = cv2.convexHull(leftEye)  # 寻找左眼轮廓
            rightEyeHull = cv2.convexHull(rightEye)  # 寻找右眼轮廓
            cv2.drawContours(self.image, [leftEyeHull], -1, (0, 255, 0), 1)  # 绘制左眼轮廓
            cv2.drawContours(self.image, [rightEyeHull], -1, (0, 255, 0), 1)  # 绘制右眼轮廓

            # 如果EAR小于阈值,开始计算连续帧,只有连续帧计数超过EYE_AR_CONSEC_FRAMES时,才会计做一次眨眼
            if ear < self.EYE_AR_THRESH:
                self.frame_counter += 1
            else:
                if self.frame_counter >= self.EYE_AR_CONSEC_FRAMES:
                    self.blink_counter += 1
                self.frame_counter = 0

            # 在图像上显示出眨眼次数blink_counter和EAR
            #cv2.putText(self.img, "Blinks:{0}".format(self.blink_counter), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255),2)
            cv2.putText(self.image, "Blinks:{0}".format(self.blink_counter), (300, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)

    def eye_aspect_ratio(self,eye):
        # print(eye)
        A = distance.euclidean(eye[1], eye[5])
        B = distance.euclidean(eye[2], eye[4])
        C = distance.euclidean(eye[0], eye[3])
        ear = (A + B) / (2.0 * C)
        return ear




if __name__ == "__main__":
    App = QApplication(sys.argv)
    ex = Ui_MainWindow()
    ex.show()
    sys.exit(App.exec_())

大部分代码是站在“巨人”的肩膀上修改的,如有冒犯,请联系我

pyqt5的QVideoWidget视频播放问题?

02-28
import sys from PyQt5.QtCore import QUrl from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent, QMediaPlaylist from PyQt5.QtMultimediaWidgets import QVideoWidget from PyQt5.QtWidgets import QApplication, QWidget class Demo(QWidget): def __init__(self): super(Demo, self).__init__() self.playlist = QMediaPlaylist(self) #实例化一个播放列表 self.video_widget = QVideoWidget(self) #实例化一个视频窗口对象 self.video_widget.resize(self.width(), self.height())#设置视频窗口的大小 self.player = QMediaPlayer(self) #实例化一个播放器 self.player.setPlaylist(self.playlist) #给播放器设置播放列表 self.player.setVideoOutput(self.video_widget) # 设置播放设备。播放设备是视频窗口对象 self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(r'D:\ss\ssss\images\video1.mp4'))) # 给播放列表添加视频源 self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(r'D:\ss\ssss\images\video2.mp4'))) self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(r'D:\ss\ssss\images\video3.mp4'))) self.playlist.setPlaybackMode(QMediaPlaylist.Loop) #设置播放模式 # QMediaPlaylist.CurrentItemOnce=0 当前内容播放一次 #QMediaPlaylist.CurrentItemInLoop=1 单曲循环 #QMediaPlaylist.Sequential=2 顺序播放 # QMediaPlaylist.Loop=3 列表循环 # QMediaPlaylist.Random=4 随机播放 self.playlist.setCurrentIndex(1) # 设置当前要进行播放文件,传入1代表播放第2个文件 self.player.setVolume(80) #设置音量 self.player.play() #播放 if __name__ == '__main__': app = QApplication(sys.argv) demo = Demo() demo.show() sys.exit(app.exec_()) ``` 没有播放,不知道问题在哪儿? ```
©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值