Skip to content

Instantly share code, notes, and snippets.

@kingardor
Last active May 6, 2021 22:09
Show Gist options
  • Save kingardor/ef77f30008faf1cbb85ac90aa3851f11 to your computer and use it in GitHub Desktop.
Save kingardor/ef77f30008faf1cbb85ac90aa3851f11 to your computer and use it in GitHub Desktop.
To display Webcam in a tkinter display box
import PIL
from PIL import Image,ImageTk
import pytesseract
import cv2
from tkinter import *
width, height = 1920, 1080
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
root = Tk()
root.bind('<Escape>', lambda e: root.quit())
lmain = Label(root)
lmain.pack()
def show_frame():
ret, frame = cap.read()
if ret:
frame = cv2.flip(frame, 1)
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)
show_frame()
root.mainloop()
@keyro90
Copy link

keyro90 commented Jan 11, 2021

VideoCapture's parameter should be an integer variable because it's an index in this case.
String value is accepted only if you want to write the entire device name, e.g. "/dev/video0".

@kingardor
Copy link
Author

VideoCapture's parameter should be an integer variable because it's an index in this case.
String value is accepted only if you want to write the entire device name, e.g. "/dev/video0".

Thanks for pointing it out. Corrected the gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment