脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - pyqt5+opencv 实现读取视频数据的方法

pyqt5+opencv 实现读取视频数据的方法

2022-09-03 10:31郭庆汝 Python

这篇文章主要介绍了pyqt5+opencv 实现读取视频数据的方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

1、openCV读取视频数据

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import cv2
 
if __name__ == '__main__':
    videoPath = "./dataSet/3700000000003_13-38-20.055.mp4"
    nameWindow = "Detection window"  # 窗体名称
    cv2.namedWindow(nameWindow)  # 设置窗体
    capture = cv2.VideoCapture(videoPath)
    if capture.isOpened():
        size = (capture.get(cv2.CAP_PROP_FRAME_WIDTH), capture.get(cv2.CAP_PROP_FRAME_HEIGHT))  # 读取帧的宽、高
        speed = capture.get(cv2.CAP_PROP_FPS)  # 获得帧速
        while True:
            ret, frame = capture.read()
            if ret:
                frame = cv2.resize(frame, (960, 540))
                cv2.imshow(nameWindow, frame)
                if cv2.waitKey(1) & 0xFF == 27:
                    break
            else:
                break
        capture.release()
        cv2.destroyAllWindows()
    else:
        print("摄像头或视频读取失败")

2、openCV集成pyqt5读取视频数据

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import cv2
import numpy as np
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
 
class Video():
    def __init__(self, capture):
        self.capture = capture
        self.currentFrame = np.array([])
    def captureNextFrame(self):
        ret, readFrame = self.capture.read()
        if (ret == True):
            self.currentFrame = cv2.resize(readFrame, (960, 540))
    def convertFrame(self):
        try:
            height, width, channel = self.currentFrame.shape
            bytesPerLine = 3 * width
            qImg = QImage(self.currentFrame.data, width, height, bytesPerLine,
                               QImage.Format_RGB888).rgbSwapped()
            qImg = QPixmap.fromImage(qImg)
            return qImg
        except:
            return None
class win(QMainWindow):
    def __init__(self, parent=None):
        super().__init__()
        self.setGeometry(250, 80, 800, 600# 从屏幕(250,80)开始建立一个800*600的界面
        self.setWindowTitle('camera')
        self.videoPath = "./dataSet/3700000000003_13-38-20.055.mp4"
        self.video = Video(cv2.VideoCapture(self.videoPath))
        self._timer = QTimer(self)
        self._timer.timeout.connect(self.play)
        self._timer.start(27)
        self.update()
        self.videoFrame = QLabel('VideoCapture')
        self.videoFrame.setAlignment(Qt.AlignCenter)
        self.setCentralWidget(self.videoFrame)          # 设置图像数据填充控件
    def play(self):
            self.video.captureNextFrame()
            self.videoFrame.setPixmap(self.video.convertFrame())
            self.videoFrame.setScaledContents(True)     # 设置图像自动填充控件
        except TypeError:
            print('No Frame')
if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = win()
    win.show()
    sys.exit(app.exec_())

pyqt5+opencv 实现读取视频数据的方法

界面美化版:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import sys
import os
import cv2
 
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import QPalette, QBrush, QPixmap
class Ui_MainWindow(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Ui_MainWindow, self).__init__(parent)
        self.timer_camera = QtCore.QTimer()  # 初始化定时器
        self.cap = cv2.VideoCapture()  # 初始化摄像头
        self.CAM_NUM = r"D:\PycharmProjects\ele_good_pyqt5\dataSet\00.flv"
        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()  # 采用QHBoxLayout类,按照从左到右的顺序来添加控件
        self.__layout_fun_button = QtWidgets.QHBoxLayout()
        self.__layout_data_show = QtWidgets.QVBoxLayout()  # 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 = 500,y = 500的位置上
        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.jpg')))
        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:
            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()      # 读取摄像头数据
        show = cv2.resize(self.image, (640, 480))
        show = cv2.cvtColor(show, cv2.COLOR_BGR2RGB)
        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("关闭")
        ok = QtWidgets.QPushButton()
        cancel = QtWidgets.QPushButton()
        msg = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, 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()
            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_())

显示效果如下所示:

pyqt5+opencv 实现读取视频数据的方法

到此这篇关于pyqt5+opencv 实现读取视频数据的文章就介绍到这了,更多相关pyqt5 opencv读取视频数据内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/guoqingru0311/article/details/122670435

延伸 · 阅读

精彩推荐
  • PythonPython中的pack和unpack的使用

    Python中的pack和unpack的使用

    这篇文章主要介绍了Python中的pack和unpack的使用,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    三月沙8312021-01-21
  • Python解决Django的request.POST获取不到内容的问题

    解决Django的request.POST获取不到内容的问题

    今天小编就为大家分享一篇解决Django的request.POST获取不到内容的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    NoneSec12222021-02-26
  • Pythondjango使用多个数据库的方法实例

    django使用多个数据库的方法实例

    这篇文章主要给大家介绍了关于django使用多个数据库的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需...

    obaby@mars5622021-09-14
  • PythonPython使用LDAP做用户认证的方法

    Python使用LDAP做用户认证的方法

    这篇文章主要介绍了Python使用LDAP做用户认证的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下...

    再见紫罗兰10012021-07-16
  • PythonPython数据处理numpy.median的实例讲解

    Python数据处理numpy.median的实例讲解

    下面小编就为大家分享一篇Python数据处理numpy.median的实例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    chaibubble11112021-01-27
  • Pythonpython适合人工智能的理由和优势

    python适合人工智能的理由和优势

    在本篇文章里小编给大家分享了关于python适合人工智能的理由和优势以及相关知识点,需要的朋友们学习下。...

    greystar_cn5252021-07-26
  • Pythonpython写入文件自动换行问题的方法

    python写入文件自动换行问题的方法

    这篇文章主要介绍了python写入文件自动换行问题的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们...

    路人甲12348232021-08-01
  • Python解决python2 绘图title,xlabel,ylabel出现中文乱码的问题

    解决python2 绘图title,xlabel,ylabel出现中文乱码的问题

    今天小编就为大家分享一篇解决python2 绘图title,xlabel,ylabel出现中文乱码的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    心雨心辰11872021-05-24