(17)Python读取摄像头并实现视频播放、暂停、指定目录保存、回放功能
读取摄像头并播放、暂停功能
- import sys
- #import scipy.io as sio
- from PyQt5 import QtGui, QtCore, QtWidgets
- #from wyc import Ui_Form
- import cv2
- import numpy as np
- class VideoCapture(QtWidgets.QWidget):
- def __init__(self, filename, parent):
- super(QtWidgets.QWidget, self).__init__()
- self.cap = cv2.VideoCapture(0)
- self.video_frame = QtWidgets.QLabel()
- parent.layout.addWidget(self.video_frame)
- def nextFrameSlot(self):
- ret, frame = self.cap.read()
- # frame = cv2.cvtColor(frame, cv2.cv.CV_BGR2RGB)
- frame2 = np.zeros((frame.shape), dtype=np.int8)
- # BGR
- frame2[:, :, 0] = frame[:, :, 2]
- frame2[:, :, 1] = frame[:, :, 1]
- frame2[:, :, 2] = frame[:, :, 0]
- img = QtGui.QImage(frame2, frame2.shape[1], frame2.shape[0], QtGui.QImage.Format_RGB888)
- pix = QtGui.QPixmap.fromImage(img)
- self.video_frame.setPixmap(pix)
- def start(self):
- self.timer = QtCore.QTimer()
- self.timer.timeout.connect(self.nextFrameSlot)
- self.timer.start(1000.0/30)
- def pause(self):
- self.timer.stop()
- def deleteLater(self):
- self.cap.release()
- super(QtGui.QWidget, self).deleteLater()
- class VideoDisplayWidget(QtWidgets.QWidget):
- def __init__(self,parent):
- super(VideoDisplayWidget, self).__init__(parent)
- self.layout = QtWidgets.QFormLayout(self)
- self.startButton = QtWidgets.QPushButton('播放', parent)
- self.startButton.clicked.connect(parent.startCapture)
- self.startButton.setFixedWidth(50)
- self.pauseButton = QtWidgets.QPushButton('暂停', parent)
- self.pauseButton.setFixedWidth(50)
- self.layout.addRow(self.startButton, self.pauseButton)
- self.setLayout(self.layout)
- class ControlWindow(QtWidgets.QMainWindow):
- def __init__(self):
- super(ControlWindow, self).__init__()
- self.setGeometry(100, 100, 800, 600)
- self.setWindowTitle("视频显示demo")
- self.capture = None
- self.matPosFileName = None
- self.videoFileName = None
- self.positionData = None
- self.updatedPositionData = {'red_x':[], 'red_y':[], 'green_x':[], 'green_y': [], 'distance': []}
- self.updatedMatPosFileName = None
- self.isVideoFileLoaded = True
- self.isPositionFileLoaded = True
- self.quitAction = QtWidgets.QAction("&Exit", self)
- self.quitAction.setShortcut("Ctrl+Q")
- self.quitAction.setStatusTip('Close The App')
- self.quitAction.triggered.connect(self.closeApplication)
- # self.openMatFile = QtWidgets.QAction("&Open Position File", self)
- # self.openMatFile.setShortcut("Ctrl+Shift+T")
- # self.openMatFile.setStatusTip('Open .mat File')
- # self.openMatFile.triggered.connect(self.loadPosMatFile)
- # self.openVideoFile = QtWidgets.QAction("&Open Video File", self)
- # self.openVideoFile.setShortcut("Ctrl+Shift+V")
- # self.openVideoFile.setStatusTip('Open .h264 File')
- # self.openVideoFile.triggered.connect(self.loadVideoFile)
- # self.mainMenu = self.menuBar()
- # self.fileMenu = self.mainMenu.addMenu('&File')
- # self.fileMenu.addAction(self.openMatFile)
- # self.fileMenu.addAction(self.openVideoFile)
- # self.fileMenu.addAction(self.quitAction)
- self.videoDisplayWidget = VideoDisplayWidget(self)
- self.setCentralWidget(self.videoDisplayWidget)
- def startCapture(self):
- if not self.capture and self.isPositionFileLoaded and self.isVideoFileLoaded:
- self.capture = VideoCapture(self.videoFileName, self.videoDisplayWidget)
- self.videoDisplayWidget.pauseButton.clicked.connect(self.capture.pause)
- self.capture.start()
- def endCapture(self):
- self.capture.deleteLater()
- self.capture = None
- # def loadPosMatFile(self):
- # try:
- # self.matPosFileName = str(QtGui.QFileDialog.getOpenFileName(self, 'Select .mat position File'))
- # self.positionData = sio.loadmat(self.matPosFileName)
- # self.isPositionFileLoaded = True
- # except:
- # print("Please select a .mat file")
- # def loadVideoFile(self):
- # try:
- # self.videoFileName = QtGui.QFileDialog.getOpenFileName(self, 'Select .h264 Video File')
- # self.isVideoFileLoaded = True
- # except:
- # print("Please select a .h264 file")
- def closeApplication(self):
- choice = QtGui.QMessageBox.question(self, 'Message','Do you really want to exit?',QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
- if choice == QtGui.QMessageBox.Yes:
- print("Closing....")
- sys.exit()
- else:
- pass
- if __name__ == '__main__':
- import sys
- app = QtWidgets.QApplication(sys.argv)
- window = ControlWindow()
- window.show()
- sys.exit(app.exec_())
回放、指定目录保存功能
- 以时间戳的形式保存视频:
- import cv2
- import datetime
- cap = cv2.VideoCapture(0)
- import os.path
- save_path = 'G:/Temp/' #以特定前缀保存视频文件到指定目录
- timeNow = "%s.avi" % (datetime.datetime.now().strftime('%Y_%m_%d_%H-%M-0%S'))
- completeName = os.path.join(save_path, timeNow)
- out = (cv2.VideoWriter(timeNow, cv2.VideoWriter_fourcc(*'PIM1'), 30.0, (640, 480))) #第三个参数是帧率
- while cap.isOpened():
- ret, frame = cap.read()
- if ret==True:
- out.write(frame)
- cv2.imshow('frame', frame)
- if cv2.waitKey(1) & 0xFF == ord('q'):
- break
- else:
- break
- # Release everything if job is finished
- cap.release()
- out.release()
- cv2.destroyAllWindows()
- 回放视频:
- import os
- def videoBack(self):
- os.startfile("G:/Tx2Project/VideoShow") #录制的视频存放文件
(17)Python读取摄像头并实现视频播放、暂停、指定目录保存、回放功能的更多相关文章
- 利用python+graphviz绘制数据结构关系图和指定目录下头文件包含关系图
作为一名linux系统下的C语言开发,日常工作中经常遇到两个问题: 一是分析代码过程中,各种数据结构互相关联,只通过代码很难理清系统中所有结构体的整体架构,影响代码消化的效率; 二是多层头文件嵌套包含 ...
- python读取文件通过正则过滤需要信息然后保存到新文件里
import osimport reimport fileinput def getDataFromFile(): rt = "/(.*)/(.*).apk" ...
- python实现上传文件到linux指定目录
今天接到一个小需求,就是想在windows环境下,上传压缩文件到linux指定的目录位置并且解压出来,然后我想了一下,这个可以用python试试写下. 环境:1.linux操作系统一台2.window ...
- 【Python】自动生成html文件查看指定目录中的所有图片
获取本目录下的pic子目录中的所有图片(jpg,png,bmp,gif等,此处以jpg文件为例),然后生成一个image.html文件,打开该html文件即可在浏览器中查看pic子目录中的所有图片. ...
- python zip压缩文件 并移动到指定目录
需要引入的3个包: import os import shutil import zipfile 1. # 创建zip文件对象your_zip_file_obj = zipfile.ZipFile(' ...
- Python 解压缩Zip和Rar文件到指定目录
#__author__ = 'Joker'# -*- coding:utf-8 -*-import urllibimport osimport os.pathimport zipfilefrom zi ...
- Python读取JSON数据,并解决字符集不匹配问题
今天来谈一谈Python解析JSON数据,并写入到本地文件的一个小例子. – 思路如下 从一个返回JSON天气数据的网站获取到目标JSON数据串 使用Python解析出需要的部分 写入到本地文件,供其 ...
- 最简单的基于FFmpeg的AVDevice例子(读取摄像头)
=====================================================最简单的基于FFmpeg的AVDevice例子文章列表: 最简单的基于FFmpeg的AVDev ...
- Python 读取图像文件的性能对比
Python 读取图像文件的性能对比 使用 Python 读取一个保存在本地硬盘上的视频文件,视频文件的编码方式是使用的原始的 RGBA 格式写入的,即无压缩的原始视频文件.最开始直接使用 Pytho ...
随机推荐
- 操作系统 - Linux操作系统 - Centos - Centos7 - 安装|命令|使用汇总
镜像: http://mirrors.aliyun.com/centos/7/isos/x86_64/http://archive.kernel.org 网络配置 - DHCP # /etc/res ...
- QML - 实现Gstreamer投屏 投屏画面遮挡
1. 背景介绍 中控端运行的操作系统是Android,中控软件主要功能有导航.收音机.媒体(音乐).蓝牙(连接).手机互联.行车辅助和系统设置等. 仪表端运行的操作系统是Linux,仪表软件主 ...
- php php-fpm、nginx和js
1 php-fpm是什么 php-fpm是php fastCGI process manager的缩写.它是php的进程管理器,对每个请求的处理都是一个进程. php-fpm管理了一个进程池,假如进程 ...
- Kubernetes服务部署解决方案
学习了K8S的基础知识,我们的目的就是解决我们服务的迁移,那么接下去通过几个案例来感受一下K8s部署带来的便捷与效率. 环境准备: 3个节点,然后我这边也安装了 Ingress. 部署wordpres ...
- [Codeforces 1214A]Optimal Currency Exchange(贪心)
[Codeforces 1214A]Optimal Currency Exchange(贪心) 题面 题面较长,略 分析 这个A题稍微有点思维难度,比赛的时候被孙了一下 贪心的思路是,我们换面值越小的 ...
- cmd常用快捷键
Crtl + Shift +Enter : 以管理员的方式进入命令行模式 ESC: 清楚当前行的内容 Alt + Enter : 全屏/退出全屏 F7 : 通过列表形式查看历史记录 F4 : 快速删除 ...
- 剑指offer-删除链表中重复的结点-链表-python ***
题目描述 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针. 例如,链表1->2->3->3->4->4->5 处理后 ...
- linux MySql 主从异步复制
[root@localhost ~]# hostname master.allentuns ###SLAVE 执行 [root@localhost ~]# sed -i 's@\(HOSTNAME=\ ...
- 合肥学院ACM集训队第一届暑假友谊赛 B FYZ的求婚之旅 D 计算机科学家 F 智慧码 题解
比赛网址:https://ac.nowcoder.com/acm/contest/994#question B FYZ的求婚之旅 思路: 然后用快速幂即可. 细节见代码: #include <i ...
- do{}while(0);里面有continue
do{}while(0);里面有continue,退出的只是do{}while(0);