Commit 9249fb89 authored by Diego André Sant'Ana's avatar Diego André Sant'Ana 🤞

Ajuste nas mensagens das threads e melhoria do extrator de frames

parent 0b802554
......@@ -44,6 +44,12 @@
<option value="E501" />
<option value="W29" />
<option value="E501" />
<option value="W29" />
<option value="E501" />
<option value="W29" />
<option value="E501" />
<option value="W29" />
<option value="E501" />
</list>
</option>
</inspection_tool>
......
This diff is collapsed.
......@@ -7,100 +7,145 @@
Selecter folder where stay videos, before select folder where extract frames.
Name: extractor_frame_movie.py
Name: extractor_frame_video.py
Author: Diego Andre Sant Ana ( diego.santana@ifms.edu.br )
"""
try:
# for Python2
import Tkinter
import tkFileDialog
except ImportError:
# for Python3
import tkinter
import filedialog as tkFileDialog
import os
from os import listdir
from os.path import isfile, join
import cv2
import threading
import tkFileDialog
from Tkinter import *
from util.utils import TimeUtils
class ExtractFM(object):
def __init__(self):
pass
def run(self,tk):
self.tk=tk
#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
self.folder_a=None
self.folder_b=None
#janela
#window
self.window = Tk()
self.window.title("Extract Frames from videos")
self.window.mainloop()
self.window.title("Extract frames from videos")
self.window.attributes('-zoomed', False)
self.window.geometry("450x250+300+300")
self.frame = Frame(self.window )
self.frame.pack(fill=X, expand=False)
self.folder_source = Button(self.frame, text="Select Folder Source", padx=5, pady=5, command = self.select_folder_source)
#find a folder with videos
self.folder_source = Button(self.frame, text="Select source folder", padx=5, pady=5, command = self.select_folder_source)
self.folder_source.pack(padx=5, pady=5, expand=True, fill=X)
#ToolTip(self.folder_source, "Select folder with videos from extract frames!")
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)
self.folder_export = Button(self.frame, text="Select Folder Source", padx=5, pady=5, command = self.select_folder_export)
self.folder_export = Button(self.frame, text="Select destination folder", padx=5, pady=5, command = self.select_folder_export)
self.folder_export.pack(padx=5, pady=5, expand=True, fill=X)
#ToolTip(self.folder_export , "Select folder to save frames!")
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)
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!")
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()
def extract_frame(self, file,caminho):
newDir= self.folder_b+"/"+file.replace(file.split(".")[-1] ,"")
def extract_frame(self, file,source,n_frame):
newDir= self.folder_b+"/"+ file.split(".")[-2]
print(newDir)
print(source)
try:
print("Create Folder:"+newDir)
os.mkdir(newDir)
print("Create Folder:"+newDir)
except OSError:
print("Folder exists:"+newDir)
cap = cv2.VideoCapture(caminho)
counter_frame = 0;
while(counter_frame<500000):
cap = cv2.VideoCapture(source)
counter_frame = 0
last_extract=0
print(n_frame)
while(True):
print(counter_frame)
ret, img= cap.read()
if(ret == False):
return
cv2.imwrite((newDir+"/"+str(counter_frame)+".png").encode('utf-8').strip(), img)
counter_frame+=1
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
cap.release()
def export_frame(self):
if self.folder_a is None:
return
if self.folder_b is None:
return
#dir='../dataset_20180816/'
if self.val_frame is None:
return
if self.val_frame==0:
return
dir=self.folder_a
listaArquivo = [f for f in listdir(dir) if isfile(join(dir, f))]
self.tk.append_log("Init process:"+ str(listaArquivo))
self.tk.write_log("Init process:"+ str(listaArquivo))
lista_thread=[]
start_time = TimeUtils.get_time()
#start_time = TimeUtils.get_time()
for r, d, f in os.walk(dir):
for file in f:
ext=file.split(".")[-1]
if ext =="avi" or "mp4"==ext :
t=threading.Thread(target=self.extract_frame,args=(file, os.path.join(r, file)))
t=threading.Thread(target=self.extract_frame,args=(file, os.path.join(r, file),self.val_frame.get()))
t.start()
lista_thread.append(t)
......@@ -109,7 +154,7 @@ class ExtractFM(object):
t.join()
end_time = TimeUtils.get_time()
#end_time = TimeUtils.get_time()
self.tk.append_log("Finish process:"+str(end_time - start_time))
def select_folder_source(self):
......
......@@ -20,13 +20,15 @@ from util.utils import ImageUtils
from util.utils import TimeUtils
import cv2
from extractor import Extractor
from tqdm import tqdm
import sys
class FeatureExtractor(object):
"""Handle the feature extraction."""
def __init__(self, extractors):
def __init__(self, extractors, tkParent=None):
"""Constructor.
Parameters
......@@ -35,6 +37,7 @@ class FeatureExtractor(object):
Initial set of active extractors.
"""
self.extractors = extractors
self.tkParent=tkParent
def extract_all(self, dataset, output_file=None, dirs=None, overwrite=True):
self.labels = []
......@@ -88,15 +91,26 @@ class FeatureExtractor(object):
dirs = classes if dirs is None else dirs
# Runs the feature extraction for all classes inside the dataset
for i,cl in enumerate(dirs):
for cl in dirs:
# start job for each extractor
th = threading.Thread(target=self.job_extractor,args=(dataset, cl, classes))
th.start()
self.threads.append(th)
self.job_extractor(dataset, cl, classes)
self.print_console("Wait a moment, the threads are processing "+str(len(self.threads)) +" images, it may be delayed depending on the size or quantity of the images!")
#Start threads
with tqdm(total=len(self.threads)) as pbar:
for t in self.threads:
t.start()
pbar.close()
for t in self.threads:
t.join()
self.print_console("Waiting for workers to finish extracting attributes from images!")
with tqdm(total=len(self.threads)) as ppbar:
for t in self.threads:
t.join()
ppbar.update(1)
ppbar.close()
self.print_console("The process was completed with "+str(len(self.threads))+" images!")
if len(self.data) == 0:
raise IException("There are no images in dataset: %s" % dataset)
......@@ -111,14 +125,14 @@ class FeatureExtractor(object):
def job_extractor(self, dataset, cl, classes):
items = sorted(os.listdir(File.make_path(dataset, cl)))
print("Processing class %s - %d itens" % (cl, len(items)))
self.print_console("Processing class %s - %d itens" % (cl, len(items)))
for item in items :
if item.startswith('.'):
continue
th = threading.Thread(target=self.sub_job_extractor,args=(item, dataset, cl, classes))
th .start()
self.threads.append(th)
......@@ -252,3 +266,13 @@ class FeatureExtractor(object):
hsize = int((float(image.shape[1] ) * float(wpercent)))
image = cv2.resize(image, (basewidth, hsize))
return image
"Method for print message in console, Window or Both"
def print_console(self,mensagem):
if(self.tkParent==None):
print(mensagem)
else:
print(mensagem)
self.tkParent.append_log( mensagem)
self.tkParent._root.update_idletasks()
This diff is collapsed.
......@@ -9,24 +9,30 @@
"""
import sys
if sys.version_info[0] < 3:
try:
# for Python2
import Tkinter as Tk
else:
import tkinter as Tk
import tkMessageBox
#import tkinter.messagebox
import tkMessageBox
import tk as tk_local
from interface import Interface, InterfaceException as IException
import tk as tk_local
#import tkinter as tk_local
except ImportError:
# for Python3
import tkinter as Tk
import tkinter.messagebox as tkMenssageBox
import tkinter as tk_local
from interface import Interface, InterfaceException as IException
from interface import Interface, InterfaceException as IException
class TkInterface(Interface):
"""Implements graphical interface and functionalities using Tkinter."""
MAX_CLASSES = 200
utils = tk_local.Utils
try:
utils = tk_local.Utils
except ImportError:
utils = tk_local.utils
def __init__(self, title):
"""Constructor.
......
......@@ -434,8 +434,8 @@ class Act(object):
"""Perform a feature extraction on all images of dataset, using the current collection of extractors.
"""
self.tk.write_log("Running extractors on all images in %s", self.dataset)
fextractor = FeatureExtractor(self.extractors)
self.tk._root.update_idletasks()
fextractor = FeatureExtractor(self.extractors,self.tk)
self.tk.append_log("%s", '\n'.join([extraction._extractor_list[extractor].label for extractor in extraction._extractor_list
if extraction._extractor_list[extractor].value == True ]))
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment