After recently having a go at using cv2 in python, I wanted to combine cv2 and Tkinter to make an application where the video from my webcam would display in a Tkinter window, sadly after searching the internet for a while on how to do this, I found no good solutions so decided to have a go myself, and this is a post showing you how to do exactly that.
The code is below with comments:
#Created by Flynn's Forge 2020, from https://flynnsforge.com/ #Imports import cv2 from tkinter import * from PIL import Image, ImageTk #Creating Tkinter Window and Label root = Tk() video = Label(root) video.pack() #Getting video from webcam vid = cv2.VideoCapture(0) #Loop which display video on the label while(True): ret, frame = vid.read() #Reads the video #Converting the video for Tkinter cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA) img = Image.fromarray(cv2image) imgtk = ImageTk.PhotoImage(image=img) #Setting the image on the label video.config(image=imgtk) root.update() #Updates the Tkinter window vid.release() cv2.destroyAllWindows()
So how does this work? Well we simply grab each frame from the video capture and convert it into something Tkinter will work with and then update the Tkinter window every new frame.