CustomTkinter
CustomTkinter copied to clipboard
Live video from IP address
I was wondering if there's a way of showing a live video in customtkinter, I know there is "tkvideoplayer" but that's only for normal video.
In ChatGPT it said to do this - it wouldn't be wise to use this code I think.
import cv2
import customtkinter as ctk
from tkinter import Label
from PIL import Image, ImageTk
# Function to capture and display frames
def update_frame():
# Read a frame from the camera stream
ret, frame = cap.read()
if ret:
# Convert the frame from BGR to RGB
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Convert the frame to a PIL Image
img = Image.fromarray(frame_rgb)
img = img.resize((640, 480)) # Resize to fit the window
# Convert the PIL Image to an ImageTk object
img_tk = ImageTk.PhotoImage(img)
# Update the label with the new frame
label.config(image=img_tk)
label.image = img_tk # Keep a reference to the image to prevent garbage collection
# Call the update_frame function after 10 milliseconds
window.after(10, update_frame)
# Set up the IP camera stream (replace the URL with your camera's stream URL)
camera_url = "rtsp://username:password@ip_address:port"
cap = cv2.VideoCapture(camera_url)
# Set up the main window
window = ctk.CTk()
window.title("Live Video Stream")
# Set up the label to display the video
label = Label(window)
label.pack()
# Start updating the frames
update_frame()
# Start the Tkinter main loop
window.mainloop()
# Release the camera when done
cap.release()
@sp5677 You can use it. Including OpenCV library with customtkinter package is not ideal.
@sp5677 You can use it. Including OpenCV library with customtkinter package is not ideal.
What's a better way?
@sp5677 Use class oriented approach with proper modularization ensuring safety and it is fine.
@sp5677 There is no video player like widget in tkinter by default, what tkVideoPlayer does is update a tk label image with the extracted frame from video (in a loop). So, the method you are using is fine, you are just updating the image of the ctk label with the captured frame from webcan using opencv.
@sp5677 There is no video player like widget in tkinter by default, what tkVideoPlayer does is update a tk label image with the extracted frame from video (in a loop). So, the method you are using is fine, you are just updating the image of the ctk label with the captured frame from webcan using opencv.
Tkinker doesn't use the GPU which makes it very slow, I decided it would be best if I used a different GUI that has GPU acceleration.