【问题标题】:showing video on the entire screen using OpenCV and Tkiner使用 OpenCV 和 Tkinter 在整个屏幕上显示视频
【发布时间】:2017-08-28 07:56:15
【问题描述】:

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

谢谢!

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

【问题讨论】:

    标签: python opencv video tkinter fullscreen


    【解决方案1】:

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

    但让我们尝试“按原样”处理您的代码,因此我们有两个选项可供使用:cv2Image。为了测试,我从 youtube (480p) 中抓取了 20 秒的“键盘猫”视频,并将每帧的大小调整为 1080p,GUI 看起来像这样(全屏 1920x1080):

    调整大小方法/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 方法改变了,@987654342 @方法添加):

    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 秒。

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

    【讨论】:

    • 您好常识,感谢您的出色回答。尝试你的代码,我得到 cv2image = cv2.resize(cv2image, self.size, interpolation=cv2.INTER_NEAREST) 错误:C:\Users\David\Downloads\opencv-master\opencv-master\modules\core\src\alloc .cpp:52: error: (-4) Failed to allocate 9191424 bytes in function cv::OutOfMemoryError ,知道为什么吗? (我使用 32 位 python)
    • 你有多少内存,你的全屏分辨率和剪辑长度是多少?无论如何,OpenCV 对平台非常敏感,所以我在 64 位 Win/64 位 Python/8 Gb RAM 上尝试了代码,并且 20 秒剪辑没有错误!但是使用Image 库调整大小呢?你试过了吗?只需评论cv2image = cv2.resize(...) 行,然后将cv2image = Image.fromarray(cv2image) 替换为cv2image = Image.fromarray(cv2image).resize(self.size, resample=Image.NEAREST)
    • 常识,或多或少相同,当我达到 17% 进程时,我收到内存错误。我在一台非常强大的 PC 上,i7 7700k + 32gb ram 在 win10 64 上。我不得不使用 32 位 python,因为我可能在 32 位中构建了 openCV/openCV contrib 模块。你认为这是我的问题吗?我可以尝试为 64 位构建 openCV
    • 如果只是因为openCV,当然可以试试。而且你的机器比我的好得多,所以我觉得值得。顺便说一句,openCV(和许多其他有用的)软件包已经为您构建了here - 只需下载并安装whlpip
    • 无论如何,您的问题是关于“如何全屏显示”而不是“为什么我的内存泄漏,我应该构建 64 位 OpenCV”。如果你真的想坚持使用 OpenCV - 创建单独的问题并描述我们在这里得到的所有内容,如果 64 位不是解决方案 - 你会吸引更多的人来解决这个问题,因为现在我们一个人在这里。但是,如果您不是 OpenCV 的丈夫 - 请尝试其他软件包,例如 ImageIO(更友好)或 scikit-image
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多