如何在 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 視窗中。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP