Show webcam sequence TkInter

后端 未结 5 2126
误落风尘
误落风尘 2020-12-08 06:15

I did a program with python, importing the OpenCV\'s libraries. Now, I\'m doing the GUI in Tkinter. I\'m trying to show the webcam in the GUI but I couldn\'t. I put the code

5条回答
  •  醉酒成梦
    2020-12-08 06:42

    A simple version of camera capture using OpenCv and Tkinter:

    import Tkinter as tk
    import cv2
    from PIL import Image, ImageTk
    
    width, height = 800, 600
    cap = cv2.VideoCapture(0)
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
    
    root = tk.Tk()
    root.bind('', lambda e: root.quit())
    lmain = tk.Label(root)
    lmain.pack()
    
    def show_frame():
        _, frame = cap.read()
        frame = cv2.flip(frame, 1)
        cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
        img = Image.fromarray(cv2image)
        imgtk = ImageTk.PhotoImage(image=img)
        lmain.imgtk = imgtk
        lmain.configure(image=imgtk)
        lmain.after(10, show_frame)
    
    show_frame()
    root.mainloop()
    

    You will need to download and install PIL...

    UPDATE:

    ... and OpenCV for this to work.

    To Install PIL, run the following command in your Terminal/Command Prompt:

    pip install Pillow or python -m pip install Pillow

    To Install OpenCV, run the following command in your Terminal/Command Prompt:

    pip install opencv-python or python -m pip install opencv-python

提交回复
热议问题