Showing Video Image on Tkinter Window with OpenCV


This is an example of minimal tkinter application that shows video image on the window using OpenCV.

 

Prerequisites

  • Python 3

 

Required Packages

Install packages if not already.

1. Python Imaging Library (Pillow)

pip install Pillow

2. OpenCV

pip install opencv-python

 

Code 

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

class MainWindow():
    def __init__(self, window, cap):
        self.window = window
        self.cap = cap
        self.width = self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)
        self.height = self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
        self.interval = 20 # Interval in ms to get the latest frame

        # Create canvas for image
        self.canvas = tk.Canvas(self.window, width=self.width, height=self.height)
        self.canvas.grid(row=0, column=0)

        # Update image on canvas
        self.update_image()

    def update_image(self):
        # Get the latest frame and convert image format
        self.image = cv2.cvtColor(self.cap.read()[1], cv2.COLOR_BGR2RGB) # to RGB
        self.image = Image.fromarray(self.image) # to PIL format
        self.image = ImageTk.PhotoImage(self.image) # to ImageTk format

        # Update image
        self.canvas.create_image(0, 0, anchor=tk.NW, image=self.image)

        # Repeat every 'interval' ms
        self.window.after(self.interval, self.update_image)

if __name__ == "__main__":
    root = tk.Tk()
    MainWindow(root, cv2.VideoCapture(0))
    root.mainloop()

 

Execute the program like this:

python3 video_on_tkinter.py

 

If you want to get the image from a video file instead of a camera, specify the file name like this:

    MainWindow(root, cv2.VideoCapture('test.mp4'))

 

 

References
[1] How to update an image on a Canvas? — Stack Overflow
[2] How do you run your own code alongside Tkinter’s event loop? — Stack Overflow
[3] Displaying a video feed with OpenCV and Tkinter — pyimagesearch
[4] Python OpenCV – show a video in a Tkinter window — Solarian Programmer

 

 

Sponsor Link

One Comment

  1. Hi Max,
    I need help with some RPi bluetooth programming for an application I am trying to build for our business.
    Do you do contract work?
    Unfortunately it is only a small project though.
    Greetings,
    Martin

Comments are closed.