0

I am having a problem where i cant find a way to display Opencv webcam video in a Tkinter frame, I would've used the basic code online but the problem is that i cant seem to make it automatically make a frame when the webcam is connected.

I've tried modifying the code i found online, But at this point i honestly don't have any idea of what i am doing.

import cv2
from tkinter import *
import PIL
from PIL import Image, ImageTk

root = Tk()

root.bind('<Escape>', lambda e: root.quit())
lmain = Label(root)
lmain.pack()

print("[INFO] Making variables")
ImageSource = 0
window_name = "AutoCam"
cap = cv2.VideoCapture(ImageSource)
print("[INFO] Made variables ")


def CheckSource():
    print("[INFO] Checking image source")
    while True:
        print("[INFO] Reading frame")
        cap = cv2.VideoCapture(ImageSource)
        while cap.isOpened():
            _, frame = cap.read()

            cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
            img = PIL.Image.fromarray(cv2image)
            imgtk = ImageTk.PhotoImage(image=img)
            lmain.imgtk = imgtk
            lmain.configure(image=imgtk)
            lmain.after(10, show_frame)

            print("[INFO] cv2.imshw done")

            if cv2.waitKey(1) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                cv2.waitKey(0)
                break


Check_root = False


def CheckRootDef():
    if Check_root:
        CheckSource()


CheckRootDef()
root.mainloop()
check_root = True
CheckRootDef()

i expect it to make a costum Tkinter window and show my webcam footage live on it, And that as soon as the webcam is detected.

stovfl
  • 14,998
  • 7
  • 24
  • 51
  • As it stands, your `while True:` is blocking `tkinter.mainloop()`. Did you get any visible? – stovfl Sep 20 '19 at 15:53
  • how can i fix this, i need to have that while true thaere – GottaAimHigherPal Sep 20 '19 at 15:57
  • i got a small frame but it does not show anything in it. – GottaAimHigherPal Sep 20 '19 at 17:19
  • You can use either this approach [cv2-videocapture](https://stackoverflow.com/questions/34851707/cv2-videocapture-error) , running the `while` in a `Thread` or this [why-capture-video-does-not-refresh-in-tkinter-loop](https://stackoverflow.com/questions/45463964/why-capture-video-does-not-refresh-in-tkinter-loop), using only `.after` without any `while` but don't copy the error using `.create_image(...` over and over again. – stovfl Sep 20 '19 at 17:35

0 Answers0