如何在Tkinter GUI中显示浏览硬盘中的视频?



我是Tkinter概念的新手,所以我正在尝试制作一个简单的GUI,我想在其中流式传输我的网络摄像头。除此之外,我还在尝试拍摄快照,并使用浏览按钮从硬盘中选择一个视频文件,并在有人需要时显示在面板上。

这是我的代码:

from PIL import Image, ImageTk
import tkinter as tk
from tkinter import filedialog, messagebox
import argparse
import datetime
import cv2
import os
class Application:
def __init__(self, output_path = "./"):
""" Initialize application which uses OpenCV + Tkinter. It displays
a video stream in a Tkinter window and stores current snapshot on disk """
self.vs = cv2.VideoCapture(0) # capture video frames, 0 is your default video camera
self.output_path = output_path  # store output path
self.current_image = None  # current image from the camera
self.root = tk.Tk()  # initialize root window
self.root.title("PyImageSearch PhotoBooth")  # set window title
# self.destructor function gets fired when the window is closed
self.root.protocol('WM_DELETE_WINDOW', self.destructor)
self.panel = tk.Label(self.root)  # initialize image panel
self.panel.pack(padx=10, pady=10)
# create a button, that when pressed, will take the current frame and save it to file
btn = tk.Button(self.root, text="Snapshot!", command=self.take_snapshot)
btn.pack(fill="both", expand=True, padx=10, pady=10)
tk.Button(self.root, text="Browse", command=self.loadtemplate, width=10).pack()
# start a self.video_loop that constantly pools the video sensor
# for the most recently read frame
self.video_loop()
def video_loop(self):
""" Get frame from the video stream and show it in Tkinter """
ok, frame = self.vs.read()  # read frame from video stream
if ok:  # frame captured without any errors
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)  # convert colors from BGR to RGBA
self.current_image = Image.fromarray(cv2image)  # convert image for PIL
imgtk = ImageTk.PhotoImage(image=self.current_image)  # convert image for tkinter
self.panel.imgtk = imgtk  # anchor imgtk so it does not be deleted by garbage-collector
self.panel.config(image=imgtk)  # show the image
self.root.after(30, self.video_loop)  # call the same function after 30 milliseconds
def loadtemplate(self):
filename = tk.filedialog.askopenfilename(filetypes=(("Template files", "*.tplate")
, ("HTML files", "*.html;*.htm")
, ("All files", "*.*")))
if filename:
try:
self.root.settings["template"].set(filename)
except:
tk.messagebox.showerror("Open Source File", "Failed to read file n'%s'" % filename)
return
def take_snapshot(self):
""" Take snapshot and save it to the file """
ts = datetime.datetime.now() # grab the current timestamp
filename = "{}.jpg".format(ts.strftime("%Y-%m-%d_%H-%M-%S"))  # construct filename
p = os.path.join(self.output_path, filename)  # construct output path
self.current_image.save(p, "JPEG")  # save image as jpeg file
print("[INFO] saved {}".format(filename))
def destructor(self):
""" Destroy the root object and release all resources """
print("[INFO] closing...")
self.root.destroy()
self.vs.release()  # release web camera
cv2.destroyAllWindows()  # it is not mandatory in this application
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-o", "--output", default="./",
help="path to output directory to store snapshots (default: current folder")
args = vars(ap.parse_args())
# start the app
print("[INFO] starting...")
pba = Application(args["output"])
pba.root.mainloop()

在此代码中,我能够获取快照,但无法找到在 #self.panel 中显示浏览视频的方法。

有人可以帮助我吗?

根据文档,可以通过传递设备源的设备索引(整数(或构造函数中的文件名(字符串(,使用相同的VideoCapture类从网络摄像机源或文件源捕获视频帧。

最新更新