【问题标题】:Running webcam and tkinter at the same time同时运行网络摄像头和 tkinter
【发布时间】:2018-09-23 18:36:23
【问题描述】:

我希望我的网络摄像头和 tkinter 同时运行。我在这里有一个代码,但问题是视频必须在 tkinter 出现之前终止。可以同时运行吗?

from tkinter import *
import cv2
import tkinter as tk

ui = Tk()
ui.state('zoomed')
canvas = tk.Canvas()
canvas.pack(fill = 'both', expand = True)
video = cv2.VideoCapture(0)
a = 0
while True:
    a+= 1
    check, frame = video.read()
    cv2.imshow('Video', frame)
    key = cv2.waitKey(1)
    if key == 27:
        break
    video.release()
    cv2.destroyAllWindows

【问题讨论】:

  • 您很可能需要单独的线程来进行 gui 管理和视频捕获
  • 由于您正在使用一系列帧进行操作,因此threading 中没有必要,这在您的情况下是一个直接的开销。用after loop 替换您的while 循环。

标签: python python-3.x tkinter video-capture cv2


【解决方案1】:

当然有可能,正如@Dunno 所提到的,您需要在单独的线程中运行它们。使用 threading 模块。

from tkinter import *
import cv2
import tkinter as tk
import threading

ui = Tk()
ui.state('normal')
canvas = tk.Canvas()
canvas.pack(fill = 'both', expand = True)


def video_stream():
  video = cv2.VideoCapture(0)
  a = 0
  while True:
    a+= 1
    check, frame = video.read()
    cv2.imshow('Video', frame)
    key = cv2.waitKey(1)
    if key == 27:
        break
  video.release()
  cv2.destroyAllWindows

th= threading.Thread(target=video_stream) #initialise the thread
th.setDaemon(True)
th.start() #start the thread

ui.mainloop() #Run your UI

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 2022-01-11
    • 2023-03-10
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多