如何在 tkinter canvas 中逐帧显示视频?

How to display the video in tkinter canvas frame by frame?

我正在处理 tkinter 和 opencv 以在 tkinter 中显示视频帧 canvas。我的代码如下:

import tkinter as tk
from PIL import ImageTk as itk
from PIL import Image
from tkinter import filedialog as fd
import cv2

window = tk.Tk()
class window_tk():
def __init__(self,main):
    self.canvas = tk.Canvas(main, bg='white' )
    self.img = itk.PhotoImage(file=self.init_img_route)
    self.bg= self.canvas.create_image(0,0,anchor = tk.NW,image=self.img)
    self.vid = None
def load_video(self):

    self.foldername = fd.askopenfilename(parent=window,initialdir="C:/",title='Select a video file to load.',filetypes=[('video files','*.wmv *.mp4 *.mov *.avi')])
    self.label_foldername.config(text='Video Load : '+self.foldername)
    self.current_pic_num=0
    try:
        self.vid = cv2.VideoCapture(self.foldername)
        frame_number =0
        print(self.vid,self.vid.isOpened())
        self.frame_count = 0
        if self.vid.isOpened():
            vid_w = self.vid.get(cv2.CAP_PROP_FRAME_WIDTH)
            vid_h = self.vid.get(cv2.CAP_PROP_FRAME_HEIGHT)
            vid_f = self.vid.get(cv2.CAP_PROP_FPS)
            ret,frame = self.vid.read()
            #cv2.imshow('frame',frame)
            frame_convert = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            #print(self.frame_count, vid_w,vid_h,vid_f,frame.shape)
            imgg = itk.PhotoImage(Image.fromarray(frame_convert))
            self.canvas.itemconfig(self.bg, image = imgg)
            self.canvas.pack(fill='both',expand=1)

#            frame_number+=1
    except IndexError:
        pass

我通过检查 cv2.imshow() 确认框架已成功加载,但 canvas 仅显示白色空图像。有什么我错过的吗?

我找到了答案,留下解决方案供我学习。

我将 imgg 更改为 self.img 并让它在 class 中全局使用。

我不知道为什么解决了这个问题所以如果有人能解释原因非常感谢。