0

I am dealing with tkinter and opencv to display frames of video in tkinter canvas. 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. Is there anything I missed ?

EJ Song
  • 123
  • 2
  • 13

1 Answers1

0

I found answer and leave the solution for my study.

I changed imgg to self.img and let it globally used in class.

I don't know why it solved the problem so if anyone can explain the reason thank you very much.

EJ Song
  • 123
  • 2
  • 13
  • 1
    See [Why does Tkinter image not show up if created in a function?](https://stackoverflow.com/questions/16424091/why-does-tkinter-image-not-show-up-if-created-in-a-function) – Henry Yik Jun 30 '21 at 06:35