Reputation: 5
i need to to add webcam window inside tkinter UI , what i actually need when the user pressed on start the webcam must appear in white box as it shown in the picture and the code down below also ive made a class that opens the webacam window and recognize faces
canvans=tkinter.Canvas(pro, width =900, height = 700, borderwidth=10, relief="solid",bg="#ffffff",
highlightbackground="#0E6655")
canvans.place(x=300,y=100)
pro.mainloop()
x=Gui()
Upvotes: 0
Views: 2862
Reputation: 142641
In comments you get link to example but I made some changes
read()
gives any framecap.release()
after using webcamimport *
is not preferredimport
import tkinter as tk # PEP8: `import *` is not preferred
from PIL import Image, ImageTk
import cv2
# --- functions --- # PEP8: all functions after imports
def show_frame():
# get frame
ret, frame = cap.read()
if ret:
# cv2 uses `BGR` but `GUI` needs `RGB`
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# convert to PIL image
img = Image.fromarray(frame)
# convert to Tkinter image
photo = ImageTk.PhotoImage(image=img)
# solution for bug in `PhotoImage`
label.photo = photo
# replace image in label
label.configure(image=photo)
# run again after 20ms (0.02s)
root.after(20, show_frame)
# --- main ---
cap = cv2.VideoCapture(0)
root = tk.Tk()
# create a Label to display frames
label = tk.Label(root)
label.pack(fill='both', expand=True) # to resize label when resize window
# start function which shows frame
show_frame()
root.mainloop()
cap.release()
BTW:
EDIT:
The same for Canvas
It uses image's ID to replace PhotoImage
on Canvas
import tkinter as tk # PEP8: `import *` is not preferred
from PIL import Image, ImageTk
import cv2
# --- functions ---
def show_frame():
global image_id # inform function to assign new value to global variable instead of local variable
# get frame
ret, frame = cap.read()
if ret:
# cv2 uses `BGR` but `GUI` needs `RGB
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# convert to PIL image
img = Image.fromarray(frame)
# convert to Tkinter image
photo = ImageTk.PhotoImage(image=img)
# solution for bug in `PhotoImage`
canvas.photo = photo
# check if image already exists
if image_id:
# replace image in PhotoImage on canvas
canvas.itemconfig(image_id, image=photo)
else:
# create first image on canvas and keep its ID
image_id = canvas.create_image((0,0), image=photo, anchor='nw')
# resize canvas
canvas.configure(width=photo.width(), height=photo.height())
# run again after 20ms (0.02s)
root.after(20, show_frame)
# --- main ---
image_id = None # default value at start (to create global variable)
cap = cv2.VideoCapture(0)
root = tk.Tk()
# create a Label to display frames
canvas = tk.Canvas(root)
canvas.pack(fill='both', expand=True)
# start function which shows frame
show_frame()
root.mainloop()
cap.release()
Upvotes: 1