0

I am expecting video capture refreshes the screen. When it was not a class it was working as I expected. Then I converted it to oop -below. It did not refresh... Then I expected "after" would do the work. Apperently I did not understand how after works? Does not it call -in my case below- root.vidImg.vid() continuously. If yes why self.cap = cv2.VideoCapture(0) does not captures and shows a new image? Thanks for the helps in advance

here is my code...

import tkinter as tk
from PIL import Image, ImageTk
import cv2



class Window(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        self.videoFrm = tk.Frame(self, width=480, bg='yellow', height=320)
        self.videoFrm.grid(row=0, column=0, sticky=tk.NW)
        self.vidImg = cnvs(self.videoFrm,self)
        self.vidImg.grid()

class cnvs(tk.Frame):
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)
        self.controller = controller

        self.canvas = tk.Canvas(self, width=480, height=320, bg='green')
        self.canvas.grid()

    def vid(self):
        # Capture video frames
        self.cap = cv2.VideoCapture(0)

        _, self.frame = self.cap.read()
        self.img = cv2.flip(self.frame, 1)

        self.cv2image = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGBA)
        self.cv2image = cv2.resize(self.cv2image, (0, 0), fx=0.2, fy=0.2)
        self.img = Image.fromarray(self.cv2image)
        self.imgtk = ImageTk.PhotoImage(image=self.img)

        self.canvas.create_image(10, 10, anchor=tk.NW, image=self.imgtk)

def main():

    root = Window()
    root.after(0, root.vidImg.vid())
    root.mainloop()


if __name__ == '__main__':
    main()

1 Answers1

0

To create an animation loop with the after method, you need to let the animation function call itself multiple times.

In your case, you could add the following method to the cnvs class:

def video_loop(self):
    self.vid()
    self.controller.after(10, self.video_loop)

and then call it just before the mainloop().

Furthermore, instead of adding a new image to the canvas for each frame, it's probably better to just change the existing image using canvas.itemconfig(...).

Josselin
  • 2,593
  • 2
  • 22
  • 35