Opencv和Tkinter:如何自动显示网络摄像头视频?

2024-04-25 11:39:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题,我找不到一个方法来显示Opencv网络摄像头视频在一个Tkinter帧,我会使用基本代码在线,但问题是,我似乎不能使它自动生成一个帧时,网络摄像头连接。你知道吗

我试过修改我在网上找到的代码,但现在我真的不知道我在做什么。你知道吗

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()

我希望它能制作一个costum Tkinter窗口,并在上面显示我的网络摄像头录像,一旦网络摄像头被检测到。你知道吗


Tags: imageimport网络infopilrootcv2frame