如何使Tkinter和OpenCV程序更具可扩展性?

2024-04-19 03:23:55 发布

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

我的程序的这一部分用于在Tkinter窗口上显示网络摄像头提要:

from tkinter import *
from PIL import Image, ImageTk
import cv2

root = Tk()

def show_frames():
    cv2image = cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2RGB)
    img = Image.fromarray(cv2image)
    imgtk = ImageTk.PhotoImage(image=img)
    label.imgtk = imgtk
    label.configure(image=imgtk)
    label.after(20, show_frames)


label = Label(root)
label.grid()
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)

show_frames()
root.mainloop()

整个程序变得相当长,很难naivgate,我正在尝试将源代码拆分为多个文件。然而,即使在代码的这个核心部分,我也遇到了麻烦。我尝试给show_frames()参数加上限,它运行函数一次,在第二帧中断

然后我试了一下:

from tkinter import *
from PIL import Image, ImageTk
import cv2

root = Tk()

def show_frames():
    cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
    cv2image = cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2RGB)
    img = Image.fromarray(cv2image)
    imgtk = ImageTk.PhotoImage(image=img)
    label.imgtk = imgtk
    label.configure(image=imgtk)
    label.after(20, show_frames)

label = Label(root)
label.grid()

show_frames()
root.mainloop()

在这一个我不确定如何“加载”到屏幕上的框架


1条回答
网友
1楼 · 发布于 2024-04-19 03:23:55

您需要将cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)移到show_frames函数之外

from tkinter import *
from PIL import Image, ImageTk
import cv2

root = Tk()

cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)

def show_frames():
    cv2image = cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2RGB)
    img = Image.fromarray(cv2image)
    imgtk = ImageTk.PhotoImage(image=img)
    label.imgtk = imgtk
    label.configure(image=imgtk)
    label.after(20, show_frames)

label = Label(root)
label.grid()

show_frames()
root.mainloop()

另外,不要使用通配符*,它可能会在将来给您带来问题

相关问题 更多 >