Python libraries are independent and thus they all can be used for different purposes while building a particular featured application. In this example, we will build an application using OpenCV and Tkinter library. OpenCV is a Python library that is used to work with Computer Vision and other artificial artifacts. Using the OpenCV module, we have to show the webcam in a tkinter window.
To create the application, you are required to install open-cv in your local machine and make sure that Python Pillow package is pre-installed. You can install these packages by typing the following commands,
pip install open-cv pip install Pillow
Once the installation has been done, we can start creating the structure and GUI of the application. The basic functionality of our application would be to open the web camera (if possible) using OpenCV. So, to display each and every captured frame, we can use Python Pillow (PIL) package which converts the frame into an Image. The Image now can be used in a Label widget that iteratively displays every captured frame in the window.
# Import required Libraries from tkinter import * from PIL import Image, ImageTk import cv2 # Create an instance of TKinter Window or frame win = Tk() # Set the size of the window win.geometry("700x350") # Create a Label to capture the Video frames label =Label(win) label.grid(row=0, column=0) cap= cv2.VideoCapture(0) # Define function to show frame def show_frames(): # Get the latest frame and convert into Image cv2image= cv2.cvtColor(cap.read(),cv2.COLOR_BGR2RGB) img = Image.fromarray(cv2image) # Convert image to PhotoImage imgtk = ImageTk.PhotoImage(image = img) label.imgtk = imgtk label.configure(image=imgtk) # Repeat after an interval to capture continiously label.after(20, show_frames) show_frames() win.mainloop()
Whenever we run the above code, it will turn on the webcam and the output will display in the tkinter window.