如何在 TkInter 窗口中显示网络摄像头?


Python 库是独立的,因此在构建特定功能应用程序时,它们都可以用于不同的用途。在此示例中,我们将使用 OpenCV 和 Tkinter 库构建一个应用程序。OpenCV 是一个 Python 库,用于计算机视觉和其他人工制品。使用 OpenCV 模块,我们必须在 tkinter 窗口中显示网络摄像头。

要创建应用程序,你需要在本地计算机上安装open-cv,并确保已预先安装Python Pillow 软件包。你可以通过键入以下命令来安装这些软件包,

pip install open-cv
pip install Pillow

安装完成后,我们可以开始创建应用程序的结构和 GUI。我们应用程序的基本功能是使用 OpenCV 打开摄像头(如果可能)。因此,要显示每个捕获的帧,我们可以使用 Python Pillow (PIL) 软件包,该软件包将帧转换为图像。现在图像可以在 Label 小部件中使用,该小部件会在窗口中迭代显示每个捕获的帧。

示例

# Import required Libraries
from tkinter import *
from PIL import Image, ImageTk
import cv2

# Create an instance of TKinter Window or frame
win = Tk()

# Set the size of the window
win.geometry("700x350")

# Create a Label to capture the Video frames
label =Label(win)
label.grid(row=0, column=0)
cap= cv2.VideoCapture(0)

# Define function to show frame
def show_frames():
   # Get the latest frame and convert into Image
   cv2image= cv2.cvtColor(cap.read()[1],cv2.COLOR_BGR2RGB)
   img = Image.fromarray(cv2image)
   # Convert image to PhotoImage
   imgtk = ImageTk.PhotoImage(image = img)
   label.imgtk = imgtk
   label.configure(image=imgtk)
   # Repeat after an interval to capture continiously
   label.after(20, show_frames)

show_frames()
win.mainloop()

输出

每当我们运行上面的代码时,它都会打开网络摄像头,并将输出显示在 tkinter 窗口中。

更新于:2021 年 6 月 8 日

7K+ 观看次数

开启您的 职业生涯

完成课程,获得认证

开始
广告
© . All rights reserved.