2017-04-03 24 views
1

私は画面全体を満たしているビデオを再生するためのGUIを作成しようとしていますが、スナップショットのボタンはまだ下に表示されています。 今、私がすることができるのは、アプリケーションウィンドウ自体をフルスクリーンに設定することです。その結果、小さなビデオが上部で再生され、ボタンの巨大な「スナップショット」ボタンが表示されます。 ビデオを画面全体に塗りつぶす方法はありますか?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/scipyからskimage/skvideoまで遊ぶための多くのオプションがあります。

コードをそのままの状態で実行しようとしていますので、遊ぶための2通りの選択肢があります:cv2Imageです。テストのために私はユーチューブ(480P)から「キーボードの猫」のビデオの20秒をつかんで、1080件まで各フレームのサイズを変更し、GUIは、この(フルスクリーン1920×1080)のようになりますの

enter image description here

サイズ変更方法/ timeit経過時間をフレームを示す:

ご覧のとおり - theese 2の間には大きな違いはので、ここでのコード(変更のみ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」「その場で」そのようなことを行います良いアイデアトン、そう(のみ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

Hey CommonSense、偉大な答えに感謝します。コード:Cv2image = cv2.resize(cv2image、self.size、補間= cv2.INTER_NEAREST) エラー:C:\ Users \ David \ Downloads \ opencv-master \ opencv-master \ modules \ core \ src \ alloc.cpp:52:error:(-4)関数cv :: OutOfMemoryErrorで9191424バイトの割り当てに失敗しました。 (私は32ビットのPythonを使用しています) – David

+0

あなたはどのくらいのRAMを持っていますか、あなたのフルスクリーンの解像度とクリップの長さは?とにかく、OpenCVはプラットフォームに非常に感覚的です.64ビットのWin/64ビットPython/8 Gb RAMでコードを試してみましたが、20秒のクリップでエラーは発生しませんでした。しかし、 'Image'ライブラリでサイズを変更するのはどうですか?それを試しましたか? 'cv2image = Image.fromArray(cv2image).resize(self.size、resample = Image.NEAREST)を使って' cv2image = cv2.resize(...) '行にコメントし、' cv2image = Image.fromarray ) '。 – CommonSense

+0

CommonSense、多かれ少なかれ、私が17%のプロセスに達したとき、私はmemエラーを取得します。私は非常に強力なPC、i7 7700k + 32GBのRAMをwin10 64に搭載しています。私はおそらく32ビットのopenCV/openCV contribモジュールをビルドしたので、32ビットのPythonを使用しなければなりませんでした。それは私の問題だと思いますか?私はopenCVを64bit用に構築しようとしています – David

関連する問題