pygame opencv读取视频帧

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

pygame opencv读取视频帧

老光头_ME2CS   2022-05-23 我要评论

由于pygame.movie.Movie.play() 只支持MPEG格式的视频,且 pygame版本大于1.9.5好像已经不支持这个模块了,所以决定使用与opencv读取视频帧的画面,利用pygame的surface刷新窗口。

有基础的小伙伴,代码还是很好理解,直接上代码

pygame.time.Clock()同步时间

import pygame
from pygame.locals import *
import cv2
import sys
import time

FPS = 30
FramePerSec = pygame.time.Clock()

video_path = './Selected Stimuli/noaudio_c_001_critical_swerve.mp4'
video = cv2.VideoCapture(video_path)

pygame.init()
pygame.display.set_caption('OpenCV Video Player on Pygame')

screen = pygame.display.set_mode((1280, 720), 0, 32)
screen.fill([0,0,0])
num = 0

while True :

    T1 = time.time()
    ret, frame = video.read()
    if ret == False:
        print('Total Time:', time.time()-T0)
        sys.exit()

    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    frame = cv2.transpose(frame)
    frame = pygame.surfarray.make_surface(frame)
    screen.blit(frame, (0,0))
    if num == 0:
        T0 = time.time()
    pygame.display.update()
    FramePerSec.tick(FPS)

    num += 1
    print('freq time:{}, frame num: {}'.format(time.time()-T1, num))

    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()

 但是存在一些问题,时间戳的耗时比视频默认时间更长。

按理说FramePerSec = pygame.time.Clock()是能够很好的控制总的时长,但是发现视频越长播放器的延迟时间越长

换成Ubuntu系统后,发现以上延迟的问题得到缓解,推测可能与Windows系统中的进程管理有关。但是视频时差别很明显,比如120s视频,实际播放时间只用了118.8s。推测可能是pygame.time.Clock()是确保单帧的刷新率与预设相同,但是由于每一帧都存在相同的时间误差,就导致误差累加的问题明显。

自编时间控制

由于以上原因无法解决,增加了一个简单的控制逻辑后可有效控制视频播放的时间戳问题

import pygame
from pygame.locals import *
import cv2
import sys
import time

video_path = 'out1.avi'
video = cv2.VideoCapture(video_path)

FPS = int(round(video.get(cv2.CAP_PROP_FPS)))

FramePerSec = pygame.time.Clock()

Width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
Height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))

pygame.init()
pygame.display.set_caption('OpenCV Video Player on Pygame')

screen = pygame.display.set_mode((Width, Height), 0, 32)
screen.fill([0,0,0])
num = 0

while True :

    if num == 0:
        T0 = time.time()

    if time.time()-T0 > num*(1./FPS):

        ret, frame = video.read()
        TimeStamp = video.get(cv2.CAP_PROP_POS_MSEC)

        if ret == False:
            print('Total Time:', time.time()-T0)
            pygame.quit()
            sys.exit()

        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        frame = cv2.transpose(frame)
        frame = pygame.surfarray.make_surface(frame)
        screen.blit(frame, (0,0))

        pygame.display.update()
        
        num += 1

    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们