In this tutorial, we will create a Python GUI desktop application using Tkinter that displays a live webcam feed and allows users to capture images using OpenCV and Pillow.
Prerequisites
Make sure you have Python 3 installed along with the required dependencies:
1 |
pip install opencv-python pillow numpy tk |
Full Code for Webcam GUI App
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
import cv2 import tkinter as tk from tkinter import Label, Button from PIL import Image, ImageTk import os class WebcamApp: def __init__(self, root): self.root = root self.root.title("Webcam Capture") self.root.geometry("800x600") self.video_source = 0 # Default webcam self.vid = cv2.VideoCapture(self.video_source) self.label = Label(root) self.label.pack() self.capture_button = Button(root, text="Capture Image", command=self.capture_image) self.capture_button.pack() self.update_frame() self.root.protocol("WM_DELETE_WINDOW", self.on_closing) def update_frame(self): ret, frame = self.vid.read() if ret: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) self.photo = ImageTk.PhotoImage(image=Image.fromarray(frame)) self.label.config(image=self.photo) self.root.after(10, self.update_frame) def capture_image(self): ret, frame = self.vid.read() if ret: filename = "captured_image.jpg" cv2.imwrite(filename, frame) print(f"Image saved as {filename}") def on_closing(self): self.vid.release() self.root.destroy() if __name__ == "__main__": root = tk.Tk() app = WebcamApp(root) root.mainloop() |
Explanation
- We use
cv2.VideoCapture(0)
to access the webcam. - The
update_frame
function continuously updates the Tkinter label with the live feed. - The
capture_image
function captures an image when the button is clicked and saves it ascaptured_image.jpg
. - The
on_closing
function ensures proper cleanup when the window is closed.
Running the Application
Save the script as webcam_app.py
and run it using:
1 |
python webcam_app.py |