[PYTHON] Sample program to display video with PyQt

I made a GUI to display videos in Python

I found the program code I made a long time ago using PyQt5 and OpenCV for Python, so I will post it as a memorandum.

@author : koharite

Display video files.
If the correct answer frame information is specified, it will be displayed superimposed on the frame.

import sys
import cv2

from PyQt5.QtWidgets import (QMainWindow, QApplication, QWidget, QHBoxLayout, QLabel, QPushButton, QAction, QStyle, QFileDialog)
from PyQt5.QtGui import(QIcon, QImage, QPixmap, QPainter, QColor)
from PyQt5.QtCore import (pyqtSlot, QTimer, Qt)

#Main window configuration
class MainWindow(QMainWindow):

    #Set the initial value of the main window
    def __init__(self):
        #Window status
        self.title = 'Movie Viewer for PDET'
        self.left = 10
        self.top = 10
        self.width = 1280
        self.height = 960

        #Video status
        self.framePos = 0
        #self.image = QImage()
        self.image = None
        self.moviePlayFlg = False
        self.imgWidth = 0
        self.imgHeight = 0
        self.frameRate = 0


    #Summarize the initialization process
    def initUI(self):
        #Set the title of the main window
        #Initial position of main window
        self.setGeometry(self.left, self.top, self.width, self.height)
        hbox = QHBoxLayout(self)

        #Set the main window menu
        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('File')
        editMenu = mainMenu.addMenu('Edit')
        optionMenu = mainMenu.addMenu('Option')
        helpMenu = mainMenu.addMenu('Help')

        #Set the menu to open the file
        fileOpenButton = QAction(self.style().standardIcon(getattr(QStyle, 'SP_FileDialogStart')), 'File Open', self)

        #Set the exit menu of the app
        exitButton = QAction(self.style().standardIcon(getattr(QStyle, 'SP_DialogCloseButton')), 'Exit', self)
        exitButton.setStatusTip('Exit application')

        #Place parts in the main window
        #Set the image drawing area
        #self.showFrameLabel = QLabel(self)
        #self.painter = QPainter()
        #self.showFramePixmap = QPixmap()
        #self.painter.drawPixmap(0,0, self.imgWidth, self.imgHeight, self.showFramePixmap)
        #self.resize(self.showFramePixmap.width(), self.showFramePixmap.height())


        #Set the video play button
        moviePlayBtn = QPushButton(self.style().standardIcon(getattr(QStyle, 'SP_MediaPlay')), 'Play', self)
        moviePlayBtn.move(20, self.height-50)

        #Set the video stop button
        movieStopBtn = QPushButton(self.style().standardIcon(getattr(QStyle, 'SP_MediaStop')), 'Stop', self)
        movieStopBtn.move(120, self.height-50)

        #Drawing update timer
        #self.updateTimer = QTimer(self)

        #Display of main window

    def openFileDialog(self):
        options = QFileDialog.Options()
        #options |= QFileDialog.DontUseNativeDialog
        inputFileName, _ = QFileDialog.getOpenFileName(self, 'Open File', '', 'Movie files(*.avi *.wmv)', options=options)
        #Show filename in status bar for debugging

        #Load video with OpenCV
        self.video = cv2.VideoCapture(inputFileName)
        print('OpenCV movie read success.')
        #Get the number of frames
        self.frameNum = self.video.get(cv2.CAP_PROP_FRAME_COUNT)
        print('movie frameNum: ', str(self.frameNum))
        #Get frame rate
        self.frameRate = self.video.get(cv2.CAP_PROP_FPS)
        print('movie frameRate: ', str(self.frameRate))

        #Show first frame
        self.framePos = 0
        self.video.set(cv2.CAP_PROP_POS_FRAMES, self.framePos)
        ret, frame = self.video.read()
        print('openCV current frame read')
        #Convert playback frame from OpenCV format to PyQt QImage
        self.image = self.openCV2Qimage(frame)
        print('convert openCV to QImage')
        self.imgWidth = self.image.width()
        self.imgHeith = self.image.height()
        print('movie properties read success')
        #self.painter.drawPixmap(0, 0, self.imgWidth, self.imgHeight, self.image)

    def moviePlay(self):
        self.moviePlayFlg = True
        self.updateTimer.start((1/self.frameRate) * 1000)

    def movieStop(self):
        self.moviePlayFlg = False

    def showNextFrame(self):
        if self.moviePlayFlg == False:

        self.framePos += 1
        #Set the playback frame position of the video with OpenCV
        self.video.set(cv2.CAP_PROP_POS_FRAMES, self.framePos)
        ret, frame = self.video.read()
        #Convert playback frame from OpenCV format to PyQt QImage
        self.image = self.openCV2Qimage(frame)
        #self.imgWidth = self.image.width()
        #self.imgHeith  self.image.height()

    def paintEvent(self, event):
        #For debugging
        print('paintEvent Start')
        painter = QPainter()
        #For debugging
        print('painter tool set')

        if self.image == None:

        #image = QtGui.QImage('./sample01.jpg')
        #x = (self.width() - self.image.width()) / 2
        #y = (self.height() - self.image.height()) / 2

        #painter.drawImage(x, y, image)
        painter.drawPixmap(0, 0, self.ImgWidth, self.imgHeight, self.image)

    def openCV2Qimage(self, cvImage):
        height, width, channel = cvImage.shape
        bytesPerLine = channel * width
        cvImageRGB = cv2.cvtColor(cvImage, cv2.COLOR_BGR2RGB)
        image = QImage(cvImageRGB, width, height, bytesPerLine, QImage.Format_RGB888)
        #image = QImage(cvImage, width, height, bytesPerLine, QImage.Format_RGB888)
        #image = image.rgbSwapped()

        return image

#Run the app
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MainWindow()

Recommended Posts

Sample program to display video with PyQt
Shell program to display multiplication tables
[PyQt] Display a multi-axis graph with QtChart
How to display python Japanese with lolipop
How to use CUT command (with sample)
Sample to convert image to Wavelet with Python
How to create sample CSV data with hypothesis
I want to display multiple images with matplotlib.
Introduction to PyQt
Sample to send slack notification with python lambda
How to display images continuously with matplotlib Note
AWS Step Functions to learn with a sample
Sample program that outputs syslog with Python logging
Schema-driven development with Responder: Try to display Swagger UI
[GCP] Try a sample to authenticate users with Firebase
It's too troublesome to display Japanese with Vim's python3.
From buying a computer to running a program with python
How to loop and play gif video with openCV
A sample to try Factorization Machines quickly with fastFM
Site summary to learn machine learning with English video
Display and shoot webcam video with Python Kivy [GUI]
Display / update the graph according to the input with PySimpleGui
Python> function> Docstrings> Description to display with help () / .__ doc__
Display USB camera video with Python OpenCV with Raspberry Pi
Convert 202003 to 2020-03 with pandas
3D display with plotly
Program to weaken Japanese
Taskbar display with tqdm
Python sample to learn XOR with genetic algorithm with neural network
Try to display various information useful for debugging with python
Add fake tilt shift effect to video with OpenCV + Python
map function-Basic Python grammar learned with an interesting sample program
[Ev3dev] How to display bmp image on LCD with python
Try to bring up a subwindow with PyQt5 and Python
How to display a list of installable versions with pyenv
Convert video to black and white with ffmpeg + python + opencv
Send push notifications to iOS apps with Python2 (with sample code)