读取摄像头并播放、暂停功能

  1. import sys
  2. #import scipy.io as sio
  3. from PyQt5 import QtGui, QtCore, QtWidgets
  4. #from wyc import Ui_Form
  5. import cv2
  6. import numpy as np
  7. class VideoCapture(QtWidgets.QWidget):
  8. def __init__(self, filename, parent):
  9. super(QtWidgets.QWidget, self).__init__()
  10. self.cap = cv2.VideoCapture(0)
  11. self.video_frame = QtWidgets.QLabel()
  12. parent.layout.addWidget(self.video_frame)
  13. def nextFrameSlot(self):
  14. ret, frame = self.cap.read()
  15. # frame = cv2.cvtColor(frame, cv2.cv.CV_BGR2RGB)
  16. frame2 = np.zeros((frame.shape), dtype=np.int8)
  17. # BGR
  18. frame2[:, :, 0] = frame[:, :, 2]
  19. frame2[:, :, 1] = frame[:, :, 1]
  20. frame2[:, :, 2] = frame[:, :, 0]
  21. img = QtGui.QImage(frame2, frame2.shape[1], frame2.shape[0], QtGui.QImage.Format_RGB888)
  22. pix = QtGui.QPixmap.fromImage(img)
  23. self.video_frame.setPixmap(pix)
  24. def start(self):
  25. self.timer = QtCore.QTimer()
  26. self.timer.timeout.connect(self.nextFrameSlot)
  27. self.timer.start(1000.0/30)
  28. def pause(self):
  29. self.timer.stop()
  30. def deleteLater(self):
  31. self.cap.release()
  32. super(QtGui.QWidget, self).deleteLater()
  33. class VideoDisplayWidget(QtWidgets.QWidget):
  34. def __init__(self,parent):
  35. super(VideoDisplayWidget, self).__init__(parent)
  36. self.layout = QtWidgets.QFormLayout(self)
  37. self.startButton = QtWidgets.QPushButton('播放', parent)
  38. self.startButton.clicked.connect(parent.startCapture)
  39. self.startButton.setFixedWidth(50)
  40. self.pauseButton = QtWidgets.QPushButton('暂停', parent)
  41. self.pauseButton.setFixedWidth(50)
  42. self.layout.addRow(self.startButton, self.pauseButton)
  43. self.setLayout(self.layout)
  44. class ControlWindow(QtWidgets.QMainWindow):
  45. def __init__(self):
  46. super(ControlWindow, self).__init__()
  47. self.setGeometry(100, 100, 800, 600)
  48. self.setWindowTitle("视频显示demo")
  49. self.capture = None
  50. self.matPosFileName = None
  51. self.videoFileName = None
  52. self.positionData = None
  53. self.updatedPositionData = {'red_x':[], 'red_y':[], 'green_x':[], 'green_y': [], 'distance': []}
  54. self.updatedMatPosFileName = None
  55. self.isVideoFileLoaded = True
  56. self.isPositionFileLoaded = True
  57. self.quitAction = QtWidgets.QAction("&Exit", self)
  58. self.quitAction.setShortcut("Ctrl+Q")
  59. self.quitAction.setStatusTip('Close The App')
  60. self.quitAction.triggered.connect(self.closeApplication)
  61. # self.openMatFile = QtWidgets.QAction("&Open Position File", self)
  62. # self.openMatFile.setShortcut("Ctrl+Shift+T")
  63. # self.openMatFile.setStatusTip('Open .mat File')
  64. # self.openMatFile.triggered.connect(self.loadPosMatFile)
  65. # self.openVideoFile = QtWidgets.QAction("&Open Video File", self)
  66. # self.openVideoFile.setShortcut("Ctrl+Shift+V")
  67. # self.openVideoFile.setStatusTip('Open .h264 File')
  68. # self.openVideoFile.triggered.connect(self.loadVideoFile)
  69. # self.mainMenu = self.menuBar()
  70. # self.fileMenu = self.mainMenu.addMenu('&File')
  71. # self.fileMenu.addAction(self.openMatFile)
  72. # self.fileMenu.addAction(self.openVideoFile)
  73. # self.fileMenu.addAction(self.quitAction)
  74. self.videoDisplayWidget = VideoDisplayWidget(self)
  75. self.setCentralWidget(self.videoDisplayWidget)
  76. def startCapture(self):
  77. if not self.capture and self.isPositionFileLoaded and self.isVideoFileLoaded:
  78. self.capture = VideoCapture(self.videoFileName, self.videoDisplayWidget)
  79. self.videoDisplayWidget.pauseButton.clicked.connect(self.capture.pause)
  80. self.capture.start()
  81. def endCapture(self):
  82. self.capture.deleteLater()
  83. self.capture = None
  84. # def loadPosMatFile(self):
  85. # try:
  86. # self.matPosFileName = str(QtGui.QFileDialog.getOpenFileName(self, 'Select .mat position File'))
  87. # self.positionData = sio.loadmat(self.matPosFileName)
  88. # self.isPositionFileLoaded = True
  89. # except:
  90. # print("Please select a .mat file")
  91. # def loadVideoFile(self):
  92. # try:
  93. # self.videoFileName = QtGui.QFileDialog.getOpenFileName(self, 'Select .h264 Video File')
  94. # self.isVideoFileLoaded = True
  95. # except:
  96. # print("Please select a .h264 file")
  97. def closeApplication(self):
  98. choice = QtGui.QMessageBox.question(self, 'Message','Do you really want to exit?',QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
  99. if choice == QtGui.QMessageBox.Yes:
  100. print("Closing....")
  101. sys.exit()
  102. else:
  103. pass
  104. if __name__ == '__main__':
  105. import sys
  106. app = QtWidgets.QApplication(sys.argv)
  107. window = ControlWindow()
  108. window.show()
  109. sys.exit(app.exec_())

回放、指定目录保存功能

  1. 以时间戳的形式保存视频:
  2. import cv2
  3. import datetime
  4. cap = cv2.VideoCapture(0)
  5. import os.path
  6. save_path = 'G:/Temp/' #以特定前缀保存视频文件到指定目录
  7. timeNow = "%s.avi" % (datetime.datetime.now().strftime('%Y_%m_%d_%H-%M-0%S'))
  8. completeName = os.path.join(save_path, timeNow)
  9. out = (cv2.VideoWriter(timeNow, cv2.VideoWriter_fourcc(*'PIM1'), 30.0, (640, 480))) #第三个参数是帧率
  10. while cap.isOpened():
  11. ret, frame = cap.read()
  12. if ret==True:
  13. out.write(frame)
  14. cv2.imshow('frame', frame)
  15. if cv2.waitKey(1) & 0xFF == ord('q'):
  16. break
  17. else:
  18. break
  19. # Release everything if job is finished
  20. cap.release()
  21. out.release()
  22. cv2.destroyAllWindows()
  23. 回放视频:
  24. import os
  25. def videoBack(self):
  26. os.startfile("G:/Tx2Project/VideoShow") #录制的视频存放文件

(17)Python读取摄像头并实现视频播放、暂停、指定目录保存、回放功能的更多相关文章

  1. 利用python+graphviz绘制数据结构关系图和指定目录下头文件包含关系图

    作为一名linux系统下的C语言开发,日常工作中经常遇到两个问题: 一是分析代码过程中,各种数据结构互相关联,只通过代码很难理清系统中所有结构体的整体架构,影响代码消化的效率; 二是多层头文件嵌套包含 ...

  2. python读取文件通过正则过滤需要信息然后保存到新文件里

    import osimport reimport fileinput def getDataFromFile():        rt = "/(.*)/(.*).apk"     ...

  3. python实现上传文件到linux指定目录

    今天接到一个小需求,就是想在windows环境下,上传压缩文件到linux指定的目录位置并且解压出来,然后我想了一下,这个可以用python试试写下. 环境:1.linux操作系统一台2.window ...

  4. 【Python】自动生成html文件查看指定目录中的所有图片

    获取本目录下的pic子目录中的所有图片(jpg,png,bmp,gif等,此处以jpg文件为例),然后生成一个image.html文件,打开该html文件即可在浏览器中查看pic子目录中的所有图片. ...

  5. python zip压缩文件 并移动到指定目录

    需要引入的3个包: import os import shutil import zipfile 1. # 创建zip文件对象your_zip_file_obj = zipfile.ZipFile(' ...

  6. Python 解压缩Zip和Rar文件到指定目录

    #__author__ = 'Joker'# -*- coding:utf-8 -*-import urllibimport osimport os.pathimport zipfilefrom zi ...

  7. Python读取JSON数据,并解决字符集不匹配问题

    今天来谈一谈Python解析JSON数据,并写入到本地文件的一个小例子. – 思路如下 从一个返回JSON天气数据的网站获取到目标JSON数据串 使用Python解析出需要的部分 写入到本地文件,供其 ...

  8. 最简单的基于FFmpeg的AVDevice例子(读取摄像头)

    =====================================================最简单的基于FFmpeg的AVDevice例子文章列表: 最简单的基于FFmpeg的AVDev ...

  9. Python 读取图像文件的性能对比

    Python 读取图像文件的性能对比 使用 Python 读取一个保存在本地硬盘上的视频文件,视频文件的编码方式是使用的原始的 RGBA 格式写入的,即无压缩的原始视频文件.最开始直接使用 Pytho ...

随机推荐

  1. 判断RecyclerView是否滚动到底部

    转:http://www.jianshu.com/p/c138055af5d2 一.首先,我们来介绍和分析一下第一种方法,也是网上最多人用的方法: public static boolean isVi ...

  2. python控制流-名词解释

    一.控制流的元素 控制流语句的开始部分通常是“条件”,接下来是一个代码块,称为“子句”. 二.控制流的条件 条件为了判断下一步如何进行,从而求布尔值的表达式.几乎所有的控制流语句都使用条件. 三.代码 ...

  3. C语言I-2019博客作业02

    这个作业属于哪个课程 C语言程序设计I 这个作业要求在哪里 C语言I-2019秋作业02 我在这个课程的目标是 学会编程及提问的技能 这个作业在哪个具体目标方面帮助我实现目标 深入了解C语言程序设计中 ...

  4. windows10下安装pygame并验证成功

    首先要确保网络正常 py -m pip install --upgrade pip python -m pip install pygame --user 然后进行验证: py -m pygame.e ...

  5. [转帖]探秘华为(二):华为和H3C(华三)的分道扬镳

    探秘华为(二):华为和H3C(华三)的分道扬镳 https://baijiahao.baidu.com/s?id=1620781715767053734&wfr=spider&for= ...

  6. 部署CM集群首次运行报错:Formatting the name directories of the current NameNode.

    1. 报错提示 Formatting the name directories of the current NameNode. If the name directories are not emp ...

  7. 悼念512汶川大地震遇难同胞——选拔志愿者 HDU 2188 博弈论 巴什博奕

    悼念512汶川大地震遇难同胞--选拔志愿者 HDU 2188 博弈论 巴什博奕 题意 对于四川同胞遭受的灾难,全国人民纷纷伸出援助之手,几乎每个省市都派出了大量的救援人员,这其中包括抢险救灾的武警部队 ...

  8. qt 部分控件 setStyleSheet 使用总结

    刚用Qt不久,但是已经感受到Qt ui设计的便捷. 总结一下最近使用的控件,把它们setStyleSheet的使用方法记录下来. 主要使用到的工具有:QToolBar,QToolBox,QPushBu ...

  9. 本地代码推送到远程git仓库

    # 1. 在远程新建一个代码仓库(如码云,github..) # 2. 将本地代码提交 git init git add * git commit -am "first init" ...

  10. python中django中间件

    一.中间件 所谓的中间件,就是存在socket和视图函数中间的一种相当于过滤的机构. 中间件共分为: (1)process_request(self,request) (2)process_view( ...