Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
843 views
in Technique[技术] by (71.8m points)

opencv - Show webcam sequence TkInter

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 in the Function because I would like with a push button see my webcam.

My code is:

def webcam():
   img= cv.QueryFrame(cap)
   cam= PhotoImage(img)
   label1 = Label(root, image=cam)
   label1.image = cam
   label1.pack()
   label1.place(x=0, y=400)

Also, I don't know how update constantly without a while cycle, because I have another push button to quit the program.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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('<Escape>', 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...