网络编程
位置:首页>> 网络编程>> Python编程>> pygame+opencv实现读取视频帧的方法示例

pygame+opencv实现读取视频帧的方法示例

作者:老光头_ME2CS  发布时间:2021-01-04 23:41:27 

标签:pygame,opencv,视频帧

由于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()

来源:https://blog.csdn.net/Forrest97/article/details/107799833

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com