2017-04-03 338 views
1

我試圖創建一個用於播放填滿整個屏幕的視頻的GUI,而Snapshot按鈕仍然可見在底部。 現在,我設法做的就是將應用程序窗口本身設置爲全屏,從而在頂部播放一個小尺寸的視頻,並在按鈕上顯示一個巨大的「快照」按鈕。 有沒有辦法讓視頻填滿整個屏幕?使用OpenCV和Tkiner在整個屏幕上顯示視頻

謝謝!

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

回答

1

如果您不關心執行時間,這不是一項艱鉅的任務!我們知道,調整圖像大小並不是普通用戶的火箭科學,但是需要一些時間來調整每一幀的大小。如果你真的想知道時間和選擇 - 有很多選擇可以從numpy/scipyskimage/skvideo

但是讓我們試着用你的代碼「按原樣」做一些事情,所以我們有兩種選擇:cv2Image。爲了測試我抓住從YouTube(480P)「鍵盤貓」視頻的20秒和調整每一幀高達1080p和GUI看起來像這樣(全屏1920×1080):

enter image description here

調整大小的方法/ timeit經過的時間顯示幀:

正如你看到的 - theese兩條SO此之間沒有大的區別是一個代碼(僅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 

但是你知道 - 做這樣的事情「飛」 ISN」 T A好主意,所以讓我們嘗試先調整所有的幀,然後做所有的東西(只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秒。

正如你所看到的 - 調整大小不是腳本的主要問題,而是一個不錯的選擇!

+0

嘿CommonSense,謝謝你的出色答案。嘗試你的代碼,我得到cv2image = cv2.resize(cv2image,self.size,interpolation = cv2.INTER_NEAREST) 錯誤:C:\ Users \ David \ Downloads \ opencv-master \ opencv-master \ modules \ core \ src \ alloc.cpp:52:錯誤:(-4)無法分配9191424字節在函數cv :: OutOfMemoryError,任何想法爲什麼? (即時通訊使用32位蟒蛇) – David

+0

你有多少內存,你的全屏分辨率和剪輯的長度?無論如何,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 )'。 – CommonSense

+0

CommonSense,或多或少相同,當我達到17%的過程時,我得到了mem錯誤。我在一臺非常強大的電腦上,i7 7700k + 32gb ram在win10 64上。我不得不使用32位python,因爲我可能在32位構建了openCV/openCV contrib模塊。你認爲這是我的問題?我可以嘗試建立64位的openCV – David