gpt4 book ai didi

python - 使用 OpenCV 和 Tkinter 在整个屏幕上显示视频

转载 作者:太空宇宙 更新时间:2023-11-03 22:48:44 26 4
gpt4 key购买 nike

我正在尝试创建一个 GUI 来播放充满整个屏幕的视频,而快照按钮在底部仍然可见。现在,我设法做的只是将应用程序窗口本身设置为全屏,从而在顶部播放一个小尺寸的视频,并在按钮上显示一个巨大的“快照”按钮。有没有办法让视频充满整个屏幕?

谢谢!

from PIL import Image, ImageTk
import Tkinter as tk
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('Cat Walking.mp4') # 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)

# 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.root.attributes("-fullscreen",True)
#self.oot.wm_state('zoomed')
self.panel.config(image=imgtk) # show the image

self.root.after(1, self.video_loop) # call the same function after 30 milliseconds

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()

最佳答案

如果您不关心执行时间,这不是一项艰巨的任务!我们知道调整图像大小对于普通用户来说并不是什么难事,但在幕后,调整每一帧的大小需要一些时间。如果你真的想知道时间和选项 - 从 numpy/scipyskimage/skvideo 有很多选项可供选择

但让我们尝试“按原样”对您的代码做一些事情,这样我们就有两个选择可以使用:cv2Image。为了进行测试,我从 youtube (480p) 上抓取了 20 秒的“键盘猫”视频,并将每一帧的大小调整为 1080p,GUI 如下所示(全屏 1920x1080):

enter image description here

调整大小方法/timeit 显示帧的耗时:

如您所见 - 这两者之间没有太大区别,所以这是一段代码(只有 Application 类和 video_loop 发生了变化):

#imports
try:
import tkinter as tk
except:
import Tkinter as tk
from PIL import Image, ImageTk
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('KeyCat.mp4') # 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.root.attributes("-fullscreen", True)

# getting size to resize! 30 - space for button
self.size = (self.root.winfo_screenwidth(), self.root.winfo_screenheight() - 30)

self.panel = tk.Label(self.root) # initialize image panel
self.panel.pack(fill='both', expand=True)

# create a button, that when pressed, will take the current frame and save it to file
self.btn = tk.Button(self.root, text="Snapshot!", command=self.take_snapshot)
self.btn.pack(fill='x', expand=True)

# 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
cv2image = cv2.resize(cv2image, self.size, interpolation=cv2.INTER_NEAREST)
self.current_image = Image.fromarray(cv2image) #.resize(self.size, resample=Image.NEAREST) # convert image for PIL
self.panel.imgtk = ImageTk.PhotoImage(image=self.current_image)
self.panel.config(image=self.panel.imgtk) # show the image

self.root.after(1, self.video_loop) # call the same function after 30 milliseconds

但是你知道 - “即时”做这样的事情不是一个好主意,所以让我们先尝试调整所有帧的大小,然后再做所有的事情(只有 Application 类和 video_loop 方法已更改,添加了 resize_video 方法):

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('KeyCat.mp4') # capture video frames, 0 is your default video camera
...
# init frames
self.frames = self.resize_video()
self.video_loop()

def resize_video(self):
temp = list()
try:
temp_count_const = cv2.CAP_PROP_FRAME_COUNT
except AttributeError:
temp_count_const = cv2.cv.CV_CAP_PROP_FRAME_COUNT

frames_count = self.vs.get(temp_count_const)

while self.vs.isOpened():
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
cv2image = cv2.resize(cv2image, self.size, interpolation=cv2.INTER_NEAREST)
cv2image = Image.fromarray(cv2image) # convert image for PIL
temp.append(cv2image)
# simple progress print w/o sys import
print('%d/%d\t%d%%' % (len(temp), frames_count, ((len(temp)/frames_count)*100)))
else:
return temp

def video_loop(self):
""" Get frame from the video stream and show it in Tkinter """
if len(self.frames) != 0:
self.current_image = self.frames.pop(0)
self.panel.imgtk = ImageTk.PhotoImage(self.current_image)
self.panel.config(image=self.panel.imgtk)
self.root.after(1, self.video_loop) # call the same function after 30 milliseconds

timeit 显示预先调整大小的帧所用时间:~78.78 秒。

如您所见 - 调整大小不是脚本的主要问题,而是一个不错的选择!

关于python - 使用 OpenCV 和 Tkinter 在整个屏幕上显示视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43184817/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com