读取摄像头并播放、暂停功能
- 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") #录制的视频存放文件