简体   繁体   English

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

[英]How to display the video in tkinter canvas frame by frame?

I am dealing with tkinter and opencv to display frames of video in tkinter canvas.我正在处理 tkinter 和 opencv 以在 tkinter 画布中显示视频帧。 my code is as following :我的代码如下:

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

I confirmed that frame has successfully loaded by checking it as cv2.imshow(), but The canvas only shows the white empty image.我通过将其检查为 cv2.imshow() 来确认该框架已成功加载,但画布仅显示白色空图像。 Is there anything I missed ?有什么我错过的吗?

I found answer and leave the solution for my study.我找到了答案并将解决方案留给我的研究。

I changed imgg to self.img and let it globally used in class.我把imgg改成了self.img,让它在课堂上全局使用。

I don't know why it solved the problem so if anyone can explain the reason thank you very much.我不知道为什么它解决了问题,所以如果有人能解释原因,非常感谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM