SoFunction
Updated on 2025-04-11

Python+OpenCV develops a video player

introduction

When it comes to OpenCV, the first thing that comes to mind may be image processing and object detection, but have you ever thought about using OpenCV to implement a video player with progress bar, speed playback, and pause functions? This article will use a practical project to take you into the deep understanding of OpenCV's video processing capabilities and unlock the following functions:

  • Basic playback/pause
  • Dynamic speed adjustment (0.5x~4x)
  • Interactive progress bar
  • Real-time timestamp display

The complete code is provided at the end of the article and can be run directly!

1. Environmental preparation

Install OpenCV

pip install opencv-python  # Python version

Prepare for a test video

Prepare a video file in MP4 or AVI format (the sample code path is /home/user/video.mp4, which the reader replaces).

2. Core function implementation

1. Basic player

import cv2

cap = ('video.mp4')
while ():
    ret, frame = ()
    if not ret:
        break
    ('Player', frame)
    if (25) == 27:  # Press ESC to exit        break
()
()

Code parsing

VideoCapture: supports multiple input sources for files, cameras, and network streams.

waitKey(25): Controls the playback speed (25ms corresponds to about 40 FPS).

3. Function expansion: Make the player more powerful

1. Play at twice the speed

Speed ​​up by adjusting the delay time of waitKey:

 = 1.0  # Initial Speedkey = (max(1, int(25 / )))  # Ensure the delay is ≥1ms

Press + to accelerate, press - to decelerate, and the speed range is limited to 0.5x~4x.

2. Progress bar and jump

Use OpenCV's sliding bar control to achieve interaction:

#Create a progress bar('Progress', 'Player', 0, total_frames, self.on_trackbar)
#Callback Functiondef on_trackbar(self, pos):
    (cv2.CAP_PROP_POS_FRAMES, pos)  # Jump to the specified frame

3. Real-time information overlay

Draw progress bars and timestamps on video frames:

def draw_overlay(self, frame):
    # Calculate the length of the progress bar    progress_width = int( * (self.current_frame / self.total_frames))
    (frame, (0, 10), (progress_width, 30), (0, 255, 0), -1)
    # Show time    (frame, f"Time: {self.current_frame/:.2f}s", (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)

4. Complete code

import cv2

class VideoPlayer:
    def __init__(self, video_path):
         = (video_path)
        if not ():
            raise ValueError("Cannot open the video file, please check the path or format")

        # Get video properties        self.total_frames = int((cv2.CAP_PROP_FRAME_COUNT))
        if self.total_frames <= 0:
            raise ValueError("The total number of video frames is invalid, please check the file format")
         = (cv2.CAP_PROP_FPS)
         = int(1000 / )  # Default frame delay (milliseconds)
        # Initialize playback control variables         = False
        self.current_frame = 0
         = 1.0  # Play speed multiple
        # Create windows and progress bars        ('OpenCV Video Player')
        ('Progress', 'OpenCV Video Player', 0, self.total_frames, self.on_trackbar)

    def on_trackbar(self, pos):
        """Progress bar callback function"""
        self.current_frame = pos
        (cv2.CAP_PROP_POS_FRAMES, pos)

    def run(self):
        while True:
            if not :
                ret, frame = ()
                if not ret:
                    # The video ends, reset to the beginning to play loop                    (cv2.CAP_PROP_POS_FRAMES, 0)
                    self.current_frame = 0
                    continue
                self.current_frame += 1

                # Update progress bar position (avoid recursive calls)                ('Progress', 'OpenCV Video Player', self.current_frame)

                # Draw progress bars and timestamps on frames                self.draw_overlay(frame)

                ('OpenCV Video Player', frame)

            # Handle keyboard events (ensure the delay is not less than 1ms)            key = (max(1, int( / )))
            if key == 27:  # ESC Exit                break
            elif key == 32:  # Pause/Continue                 = not 
            elif key == ord('+'):  # Accelerate                 = min(4.0,  + 0.5)
                print(f"Accelerate to {}x")
            elif key == ord('-'):  # slow down                 = max(0.5,  - 0.5)
                print(f"Reduce to {}x")

        ()
        ()

    def draw_overlay(self, frame):
        """Draw progress bars, time and speed information"""
        # Progress bar: Based on video width calculation        video_width = [1]
        progress_ratio = self.current_frame / self.total_frames
        progress_width = int(video_width * progress_ratio)
        (frame, (0, 10), (progress_width, 30), (0, 255, 0), -1)

        # Timestamp        current_time = self.current_frame / 
        time_text = f"Time: {current_time:.2f}s"
        (frame, time_text, (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)

        # Play speed        speed_text = f"Speed: {:.1f}x"
        (frame, speed_text, (10, 100), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)

if __name__ == "__main__":
    player = VideoPlayer('/home/Videos/movie/1.mp4')  # Replace with your video path    ()

This is the end of this article about developing a video player in Python + OpenCV. For more related Python OpenCV video playback content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!