分别使用tkinter,pygame,OpenCV播放视频,发现均有视频播放变慢的现象,源码如下:
使用tkinter,OpenCV播放视频:
from tkinter import *
import cv2
from PIL import Image, ImageTk
def video_play():
while video.isOpened():
ret, frame = video.read() # 读取照片
# print('读取成功')
if ret == True:
img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA) # 转换颜色使播放时保持原有色彩
current_image = Image.fromarray(img).resize((1920,1080)) # 将图像转换成Image对象
imgtk = ImageTk.PhotoImage(image=current_image)
movieLabel.imgtk = imgtk
movieLabel.config(image=imgtk)
movieLabel.update() # 每执行以此只显示一张图片,需要更新窗口实现视频播放
else:
break
root = Tk()
root.overrideredirect(True)
root.state("zoomed")
movieLabel = Label(root,width=1920,height=1080) # 创建一个用于播放视频的label容器
movieLabel.pack()
while True:
video = cv2.VideoCapture(r"E:\放松\xjj\掠影\原神\1612179174bfee75ebffaca79a.mp4_last.mp4") # 使用opencv打开本地视频文件
video_play() # 调用video_play实现视频播放
mainloop()
使用pygame,OpenCV播放视频:
import pygame
import sys
import cv2
import numpy as np
import os
import moviepy.editor as mpy
if __name__ == '__main__':
# 截取背景音乐
# audio_background = mpy.AudioFileClip('cs1.mp4')
#
# audio_background.write_audiofile('cs1.mp3')
pygame.init() # 初始化pygame
FPS = 100
#设置窗口位置
os.environ['SDL_VIDEO_WINDOW_POS']="%d,%d" % (5,30)
FPSClock = pygame.time.Clock()
size = width, height = 960, 540 # 设置窗口大小
screen = pygame.display.set_mode(size) # 显示窗口
color = (255, 255, 255) # 设置颜色
ogg=pygame.mixer.Sound("cs1.mp3")
#pygame.mixer.music.load("")
videoCapture = cv2.VideoCapture("cs2.mp4")
ogg.play()
while True:
a=pygame.time.get_ticks()
if videoCapture.isOpened():
#从opncv读一段视频进来
ret, frame = videoCapture.read()
if ret :
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# frame = np.asarray(frame.resize((1920, 1080)))
frame = cv2.resize(frame,(960,540),interpolation=cv2.INTER_CUBIC)
frame = np.rot90(frame, k=-1)
frame = pygame.surfarray.make_surface(frame)
frame=pygame.transform.flip(frame,False,True)
screen.blit(frame, (0,0))
for event in pygame.event.get(): # 遍历所有事件
if event.type == pygame.QUIT: # 如果单击关闭窗口,则退出
sys.exit()
pygame.display.flip() # 更新全部显示
FPSClock.tick(FPS)
pygame.time.get_ticks()
使用OpenCV播放视频:
import cv2
import numpy as np
# import moviepy.editor as mpy
import pygame
pygame.init()
# ogg=pygame.mixer.Sound("cs1.mp3")
# 背景音乐
cap = cv2.VideoCapture("cs1.mp4")
fps = cap.get(cv2.CAP_PROP_FPS)
# ogg.play()
while (True):
# 读帧
ret, frame = cap.read()
# 显示图像
cv2.imshow("video", cv2.resize(frame,(960,540),interpolation=cv2.INTER_CUBIC))
# 图像的按比例压缩,
if cv2.waitKey(int(1000/fps)) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()