extractor_frame_video.py 6.03 KB
Newer Older
1 2 3 4 5 6 7 8 9

#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
    Extract frames from video

    Selecter folder where stay videos, before select folder where extract frames.

10
    Name: extractor_frame_video.py
11 12
    Author: Diego Andre Sant Ana  ( diego.santana@ifms.edu.br  )
"""
13 14
try:
    # for Python2
15
    import Tkinter as Tk
16
    import tkFileDialog
17
    from Tkinter import *
18 19
except ImportError:
    # for Python3
20 21 22
    import tkinter as Tk
    from tkinter import filedialog as tkFileDialog
    from tkinter import *
23 24 25 26 27
import os
from os import listdir
from os.path import isfile, join
import cv2
import threading
28 29


30 31
#
#from util.utils import TimeUtils
32 33


34 35


36 37 38 39 40
class ExtractFM(object):

    def __init__(self):

        pass
41 42 43
    #Method Run, you can passa tkParent to manipulate objet to tk parent, this code use to console to print process extract frame movies.
    def run(self,tkParent):
        self.tk=tkParent
44 45
        self.folder_a=None
        self.folder_b=None
46
        #window
47
        self.window = Tk()
48 49
        self.window.mainloop()
        self.window.title("Extract frames from videos")
50 51 52 53
        self.window.attributes('-zoomed', False)
        self.window.geometry("450x250+300+300")
        self.frame = Frame(self.window )
        self.frame.pack(fill=X, expand=False)
54 55
        #find a folder with videos
        self.folder_source = Button(self.frame, text="Select source folder", padx=5, pady=5, command = self.select_folder_source)
56
        self.folder_source.pack(padx=5, pady=5, expand=True, fill=X)
57
        #ToolTip(self.folder_source, "Select folder with videos from extract frames!")
58 59 60 61 62

        self.label_a =Label(self.frame, text="Folder no selected", padx=5, pady=5)
        self.label_a.pack(padx=5, pady=5, expand=True, fill=X)


63
        self.folder_export = Button(self.frame, text="Select destination folder", padx=5, pady=5, command = self.select_folder_export)
64
        self.folder_export.pack(padx=5, pady=5, expand=True, fill=X)
65
        #ToolTip(self.folder_export , "Select folder to save frames!")
66 67 68 69

        self.label_b =Label(self.frame, text="Folder no selected", padx=5, pady=5)
        self.label_b.pack(padx=5, pady=5, expand=True, fill=X)

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
        self.label_c =Label(self.frame, text="Enter in how many frames a frame will be extracted ", padx=5, pady=5)
        self.label_c.pack(padx=5, pady=5, expand=True, fill=X)
        #number de frame by extract one picture
        self.val_frame=IntVar()
        self.val_frame.set(1)

        self.spinbox = Spinbox(self.frame, from_=1.0, to=100.0)

        self.spinbox.configure(activebackground="#f9f9f9")
        self.spinbox.configure(background="white")

        self.spinbox.configure(buttonbackground="wheat")
        self.spinbox.configure(disabledforeground="#b8a786")
        self.spinbox.configure(from_="1.0")
        self.spinbox.configure(highlightbackground="black")
        self.spinbox.configure(selectbackground="#c4c4c4")
        self.spinbox.configure(textvariable=self.val_frame)
        self.spinbox.configure(to="100.0")
        self.spinbox.pack(padx=5, pady=5, expand=True, fill=X)
        #ToolTip(self.spinbox , "Select between 1 an 100 to extract frame each the number selected!Example: Select 30 to extract 1 frame each 30 fps!")

91 92 93 94 95 96
        self.buttonOpen = Button(self.frame, text="Run Extract", padx=5, pady=5, command = self.export_frame)
        self.buttonOpen.pack(padx=5, pady=5, expand=True, fill=X)
          # Open the GUI
        self.window.mainloop()


97
    def extract_frame(self, file,source,n_frame):
98

99 100 101
      newDir= self.folder_b+"/"+ file.split(".")[-2]
      print(newDir)
      print(source)
102 103
      try:
        os.mkdir(newDir)
104
        print("Create Folder:"+newDir)
105 106 107
      except OSError:
        print("Folder exists:"+newDir)

108 109 110 111 112
      cap = cv2.VideoCapture(source)
      counter_frame = 0
      last_extract=0
      print(n_frame)
      while(True):
113 114 115 116 117
            print(counter_frame)
            ret, img= cap.read()
            if(ret == False):
                return
            counter_frame+=1
118 119 120 121 122
            print(str(n_frame+last_extract==counter_frame))
            if( n_frame+last_extract==counter_frame):
                cv2.imwrite((newDir+"/"+str(counter_frame)+".png").encode('utf-8').strip(), img)
                last_extract+=n_frame

123 124 125 126 127

      cap.release()


    def export_frame(self):
128

129 130 131 132
      if self.folder_a is None:
          return
      if self.folder_b is None:
          return
133 134 135 136 137
      if self.val_frame is None:
          return
      if self.val_frame==0:
          return

138 139
      dir=self.folder_a
      listaArquivo = [f for f in listdir(dir) if isfile(join(dir, f))]
140
      self.tk.write_log("Init process:"+ str(listaArquivo))
141 142
      lista_thread=[]

143
      #start_time = TimeUtils.get_time()
144 145 146 147 148
      for r, d, f in os.walk(dir):

        for file in f:
            ext=file.split(".")[-1]
            if  ext =="avi" or "mp4"==ext  :
149
               t=threading.Thread(target=self.extract_frame,args=(file, os.path.join(r, file),self.val_frame.get()))
150 151 152 153 154 155 156 157
               t.start()
               lista_thread.append(t)

      self.tk.append_log("Threads running:"+str(threading.activeCount()))
      for t in (lista_thread):
         t.join()


158
      #end_time = TimeUtils.get_time()
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
      self.tk.append_log("Finish process:"+str(end_time - start_time))

    def select_folder_source(self):
        self.folder_a=None
        options = {

            'title': 'Auto select all videos from folder(AVI or MP4)',
            'filetypes': (("File MP4", '*.mp4'), ('File AVI', '*.avi'))

        }
        filename = tkFileDialog.askdirectory()
        if(filename != ''):
            self.folder_a = filename
        self.label_a.configure(text=self.folder_a )
        self.window.update_idletasks()

    def select_folder_export(self):
        self.folder_b=None
        options = {

            'title': 'Select folder to export frames(PNG)',
            'filetypes': (('File PNG', '*.png'))

        }
        filename = tkFileDialog.askdirectory()#askopenfilename(**options)
        if(filename != ''):
            self.folder_b = filename
        self.label_b.configure(text=self.folder_b )
        self.window.update_idletasks()
#tela=ExtractFM().run()