I wrote a code for yolo implementation with PyTorch in Colab. I can do the training, but I cannot save the model's weights. I keep getting a 'ran out of input' error. Is there any solution?
Code:
"""
Main file for training Yolo model on Pascal VOC dataset
"""
import torch
import torchvision.transforms as transforms
import torch.optim as optim
import torchvision.transforms.functional as FT #resim transformları için
from tqdm import tqdm #progressbar için
from torch.utils.data import DataLoader
from model import Yolov1
from dataset import VOCDataset
from utils import (
non_max_suppression,
mean_average_precision,
intersection_over_union,
cellboxes_to_boxes,
get_bboxes,
plot_image,
save_checkpoint,
load_checkpoint,
)
from loss import YoloLoss
seed = 123
torch.manual_seed(seed) #same datasets loading
# Hyperparameters etc.
LEARNING_RATE = 2e-5
DEVICE = "cuda" if torch.cuda.is_available else "cpu"
BATCH_SIZE = 16
WEIGHT_DECAY = 0 #sadece bir batchte train yapmak için 0 dedik yani regularizasyon yapmıyoruz
EPOCHS = 1000
NUM_WORKERS = 2
PIN_MEMORY = True
LOAD_MODEL = True
LOAD_MODEL_FILE = "/content/drive/MyDrive/YOLO 5 adım/archive/best.pt" #over fit olan modeli aldık
IMG_DIR = "/content/drive/MyDrive/YOLO 5 adım/archive/images"
LABEL_DIR = "/content/drive/MyDrive/YOLO 5 adım/archive/labels"
class Compose(object): #buradaki neden, göndereceğimiz dönüşümümüzün yalnızca resim üzerinde işlemesi çünkü sadece resize yapıyoruz
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, img, bboxes):
for t in self.transforms:
img, bboxes = t(img), bboxes
return img, bboxes
transform = Compose([transforms.Resize((448, 448)), transforms.ToTensor(),]) #resize yapıp tensöre çevirdik
def train_fn(train_loader, model, optimizer, loss_fn): #tüm datasette bir training döngüsü olacak
loop = tqdm(train_loader, leave=True) #progressbar videosunda varmış
mean_loss = []
for batch_idx, (x, y) in enumerate(loop):
x, y = x.to(DEVICE), y.to(DEVICE)
out = model(x)
loss = loss_fn(out, y)
mean_loss.append(loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
# update progress bar progress barda her batchteki lossu göreceğiz
loop.set_postfix(loss=loss.item())
print(f"Mean loss was {sum(mean_loss)/len(mean_loss)}")
def main():
model = Yolov1(split_size=7, num_boxes=2, num_classes=20).to(DEVICE)
optimizer = optim.Adam(
model.parameters(), lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY
)
loss_fn = YoloLoss()
**if LOAD_MODEL:
load_checkpoint(torch.load(LOAD_MODEL_FILE), model, optimizer) ** I got the error from this line
train_dataset = VOCDataset(
"/content/drive/MyDrive/YOLO 5 adım/archive/8examples.csv", #eğer tüm dataseti istiyorsak train.csv yaparız biz burada 100 örnek aldık sadece
transform=transform,
img_dir=IMG_DIR,
label_dir=LABEL_DIR,
)
test_dataset = VOCDataset( #test kısmı
"/content/drive/MyDrive/YOLO 5 adım/archive/test.csv", transform=transform, img_dir=IMG_DIR, label_dir=LABEL_DIR,
)
train_loader = DataLoader(
dataset=train_dataset,
batch_size=BATCH_SIZE,
num_workers=NUM_WORKERS,
pin_memory=PIN_MEMORY,
shuffle=True,
drop_last=False,#8 tanede denerken burayı false yaptık eğer çok az örnekte deniyorsak false fazla örnekte deniyorsak true yapıyoruz. çok az örnek yani tek bir batchte gerçeklesen örnekse false
)
test_loader = DataLoader(
dataset=test_dataset,
batch_size=BATCH_SIZE,
num_workers=NUM_WORKERS,
pin_memory=PIN_MEMORY,
shuffle=True,
drop_last=True,
)
for epoch in range(EPOCHS):
for x, y in train_loader: #BU KISIM GÖRSELLEŞTİRME İÇİN SONUCU BİZE GÖSTERİYOR TEK TEK RESİMLERDE
x = x.to(DEVICE) #Bu kısmı uygularken yukarıda hiperparametreler kısmındaki LOAD_MODAL'ı True yapmamız gerekiyor.
for idx in range(8):
bboxes = cellboxes_to_boxes(model(x))
bboxes = non_max_suppression(bboxes[idx], iou_threshold=0.5, threshold=0.4, box_format="midpoint")
plot_image(x[idx].permute(1,2,0).to("cpu"), bboxes)
import sys
sys.exit()
pred_boxes, target_boxes = get_bboxes( train_loader, model, iou_threshold=0.5, threshold=0.4 )
mean_avg_prec = mean_average_precision(
pred_boxes, target_boxes, iou_threshold=0.5, box_format="midpoint"
)
print(f"Train mAP: {mean_avg_prec}") #her epoch için yazdırdık
if mean_avg_prec > 0.9:
checkpoint = {
"state_dict": model.state_dict(),
"optimizer": optimizer.state_dict(),
}
save_checkpoint(checkpoint, filename=LOAD_MODEL_FILE) #kaydetmek için buu
import time
time.sleep(10)
train_fn(train_loader, model, optimizer, loss_fn)
if __name__ == "__main__":
main()
https://colab.research.google.com/drive/1l6Z86Qk8qu7Oo7fV6YNaWmJRFB9NPjCv?usp=sharing
I got error from this line (in the picture)
#save_checkpoint function from utils
def save_checkpoint(state, filename="my_checkpoint.pth.tar"):
print("=> Saving checkpoint")
torch.save(state, filename)
def load_checkpoint(checkpoint, model, optimizer):
print("=> Loading checkpoint")
model.load_state_dict(checkpoint["state_dict"])
optimizer.load_state_dict(checkpoint["optimizer"])
I see that your code is implementation by Youtuber "Aladdin Persson"
if i see the load_checkpoint , this is it.
def load_checkpoint(checkpoint, model, optimizer):
print("=> Loading checkpoint")
model.load_state_dict(checkpoint["state_dict"])
optimizer.load_state_dict(checkpoint["optimizer"])
When you are training your model for 1st time, you should have LOAD_MODEL = False &
Once the check point is saved by this name "overfit.pth.tar" , then only you can load it..
I have tested the code and it works
Related
I use tf.data.dataset to import data into model. I have created a simple reproducible code to show the idea. I save the trained model (please refer to the code below), and once I restore the model to run it on the test data I get to error that the iterator has not been initialized. Please see the error below for more details:
FailedPreconditionError (see above for traceback): GetNext() failed
because the iterator has not been initialized. Ensure that you have
run the initializer operation for this iterator before getting the
next element.
[[Node: IteratorGetNext = IteratorGetNext[output_shapes=[[?,10],
[?,1]], output_types=[DT_FLOAT, DT_FLOAT],
_device="/job:localhost/replica:0/task:0/device:CPU:0"](Iterator)]]
[[Node: IteratorGetNext/_39 = _Recv[client_terminated=false,
recv_device="/job:localhost/replica:0/task:0/device:GPU:0",
send_device="/job:localhost/replica:0/task:0/device:CPU:0",
send_device_incarnation=1, tensor_name="edge_7_IteratorGetNext",
tensor_type=DT_FLOAT,
_device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]
How can I address this issue? Here's the reproducible code:
import tensorflow as tf
import os
import numpy as np
import math
features=np.random.randn(100,10)
features_test=np.random.randn(10,10)
y=np.random.randn(100,1)
y_test=np.random.randn(10,1)
feature_size=features.shape[1]
state_size=5
learning_rate=0.001
graph = tf.Graph()
with graph.as_default():
batch_size_tensor = tf.placeholder(tf.int64,name="Batch_tensor")
X,Y = tf.placeholder(tf.float32,
[None,feature_size],"X"),tf.placeholder(tf.float32,[None,1],name="Y")
dataset =tf.data.Dataset.from_tensor_slices((X,Y)).batch(batch_size_tensor).repeat()
iter = dataset.make_initializable_iterator()
x_inputs,y_outputs = iter.get_next()
Wx = tf.Variable(tf.truncated_normal([feature_size, state_size], stddev=2.0 / math.sqrt(state_size)),name="Visual_weights_layer1")
bx= tf.Variable(tf.zeros([state_size]),name="Visual_bias_layer1")
x_hidden_state=tf.matmul(x_inputs, Wx)+bx
x_hidden_state = tf.contrib.layers.batch_norm(x_hidden_state, epsilon=1e-5)
vx=tf.nn.relu(x_hidden_state)
W_final = tf.Variable(tf.truncated_normal([state_size, 1], stddev=2.0 / math.sqrt(state_size)),name="FinalLayer_weights")
by=tf.Variable(tf.zeros([1]),name="FinalLayer_bias")
predictions = tf.add(tf.matmul(vx, W_final), by,name="preds")
loss = tf.losses.mean_squared_error(y_outputs,predictions)
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)
init = tf.global_variables_initializer()
saver = tf.train.Saver()
num_steps=100
batch_size=1
saver_path_model='tmp/testmodel'
export_path_model='tmp/testmodel.meta'
with tf.Session(graph=graph) as sess:
sess.run(init)
sess.run(iter.initializer, feed_dict={X: features, Y: y,
batch_size_tensor: batch_size})
print('initialized.')
for step in range(num_steps):
_, loss_val = sess.run([optimizer, loss])
print (loss_val)
saver.save(sess, saver_path_model)
saver.export_meta_graph(filename=export_path_model)
sess = tf.Session()
new_saver = tf.train.import_meta_graph(export_path_model)
new_saver.restore(sess, saver_path_model)
graph = tf.get_default_graph()
feed = {"X:0": features_test,"Y:0": y_test}
predictions_test = sess.run(["preds:0"], feed_dict=feed)
I saved my model as follows
saver = tf.train.Saver()
with tf.Session() as session:
session.run(tf.global_variables_initializer())
...
# after all training
save_path = saver.save(session, "logs/trained_model.ckpt")
print("Model saved: {}".format(save_path))
Then to load it
saver = tf.train.Saver()
# Initialize a session so that we can run TensorFlow operations
with tf.Session() as session:
# here is important, you need to load weights not initialize
saver.restore(session, "logs/trained_model.ckpt")
# then evaluate
official doc has more examples
https://www.tensorflow.org/api_docs/python/tf/train/Saver
I am trying to do a multigraph window for plotting different data using pyqtgraph. I have a working version with no threads using timers for getting the data. I also tried a threaded version but it seems to have no performance boost when use htop for visually inspecting the CPU Usage.
I am new to GUIs and Threads so I followed this code that I saw in a youtube tutorial. It uses a QThread to get the CPU usage using psutil.cpu_percent in intervals of 0.1 seconds and then updates a progress bar.
import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
import progress
import sysinfo
class MainUIClass(QtGui.QMainWindow, progress.Ui_MainWindow):
def __init__(self, parent = None):
super(MainUIClass, self).__init__(parent)
self.setupUi(self)
self.threadClass = ThreadClass()
self.threadClass.start()
self.connect(self.threadClass, QtCore.SIGNAL('CPU_VALUE'),
self.updateProgressBar)
def updateProgressBar(self, val):
self.progressBar.setValue(val)
class ThreadClass(QtCore.QThread):
def __init__(self, parent = None):
super(ThreadClass, self).__init__(parent)
def run(self):
while 1:
val = sysinfo.getCPU()
self.emit(QtCore.SIGNAL('CPU_VALUE'), val)
if __name__ == '__main__':
a = QtGui.QApplication(sys.argv)
app = MainUIClass()
app.show()
a.exec_()
I tried using cProfile for comparing performance but it throws lot of stuff that couldn't read, so I use the example of the progress bar to average the cpu usage after 10 seconds. Sorry if my measure performance method is so poor.
My two codes for benchmarking are
Threaded Version with a very consistent average CPU Usage of 64%:
import sys
from pyqtgraph.Qt import QtCore
from pyqtgraph.Qt import QtGui
import pyqtgraph as pg
import numpy as np
import time
class GraphWindow_Thread(pg.GraphicsWindow):
def __init__(self, rows, cols, titles):
super(GraphWindow_Thread, self).__init__()
# Code to draw the GUI
self.rows = rows
self.cols = cols
self.titles = titles
self.plots = [] # List of PlotItems
self.curves = [] # List of PlotDataItems in each PlotItem
for i in range(self.rows):
for j in range(self.cols):
p = self.addPlot()
self.plots.append(p)
if titles != [] or len(titles) == 1:
p.setLabel('left', self.titles[i+j+1])
p.setDownsampling(mode='peak')
p.setClipToView(True)
pp = p.plot(pen=(155, 255, 50))
pp1 = p.plot(pen=(55, 130, 255))
self.curves.append((pp, pp1))
self.nextRow()
# Thread to get the data and redraw plots
self.thread_graph = DataThread()
self.thread_graph.start()
self.connect(self.thread_graph, QtCore.SIGNAL('DATA_VALUE'),
self.update_plots)
def set_titles(self, titles):
for i, p in enumerate(self.plots):
p.setLabel('left', titles[i])
def update_plots(self, data, dataD):
for curve in self.curves:
curve[0].setData(data)
curve[1].setData(dataD)
class DataThread(QtCore.QThread):
def __init__(self, parent = None):
super(DataThread, self).__init__(parent)
def run(self):
while 1:
data = np.random.random((30,))
dataD = np.random.random((30,))
self.emit(QtCore.SIGNAL('DATA_VALUE'), data, dataD)
time.sleep(.1)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
gui = GraphWindow_Thread(2,3,[])
gui.show()
app.exec_()
No Thread Version with a very consistent average CPU Usage of 65%:
import sys
from pyqtgraph.Qt import QtCore
from pyqtgraph.Qt import QtGui
import pyqtgraph as pg
import numpy as np
import time
class GraphWindow(pg.GraphicsWindow):
def __init__(self, rows, cols, titles):
super(GraphWindow, self).__init__()
# Code to draw the GUI
self.rows = rows
self.cols = cols
self.titles = titles
self.plots = [] # List of PlotItems
self.curves = [] # List of PlotDataItems in each PlotItem
for i in range(self.rows):
for j in range(self.cols):
p = self.addPlot()
self.plots.append(p)
if titles != [] or len(titles) == 1:
p.setLabel('left', self.titles[i+j+1])
p.setDownsampling(mode='peak')
p.setClipToView(True)
pp = p.plot(pen=(155, 255, 50))
pp1 = p.plot(pen=(55, 130, 255))
self.curves.append((pp, pp1))
self.nextRow()
# Timer to redraw plots
timer = QtCore.QTimer(self)
self.connect(timer, QtCore.SIGNAL('timeout()'),self.update_plots)
timer.start(100)
def set_titles(self, titles):
for i, p in enumerate(self.plots):
p.setLabel('left', titles[i])
def update_plots(self):
np.random.seed()
data = np.random.random((30,))
dataD = np.random.random((30,))
for curve in self.curves:
curve[0].setData(data)
curve[1].setData(dataD)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
gui = GraphWindow(2,3,[])
gui.show()
app.exec_()
The full app is meant to be a window with multiple tabs, each one with a GraphWindow in which each graph uses a Thread for plotting different data.
What am I missing? Why my threaded version does not represent a performance improvement?
I am trying to use the Python Tkinter .config() method to update some message text. I can't get it to work. What might I be doing wrong (see the update_message method):
#!/usr/bin/python
import alsaaudio as aa
import audioop
import Tkinter as tk
import tkFont
import threading
import Queue
# styles
BACKROUND_COLOR = '#000000'
TYPEFACE = 'Unit-Bold'
FONT_SIZE = 50
TEXT_COLOR = '#777777'
TEXTBOX_WIDTH = 400
# text
TITLE = 'listen closely'
SCORE_MESSAGE = 'your score:\n '
END_MESSAGE = 'too loud!\ntry again'
# configuration
DEVICE = 'hw:1' # hardware sound card index
CHANNELS = 1
SAMPLE_RATE = 8000 # Hz // 44100
PERIOD = 256 # Frames // 256
FORMAT = aa.PCM_FORMAT_S8 # Sound format
NOISE_THRESHOLD = 3
class Display(object):
def __init__(self, parent, queue):
self.parent = parent
self.queue = queue
self._geom = '200x200+0+0'
parent.geometry("{0}x{1}+0+0".format(
parent.winfo_screenwidth(), parent.winfo_screenheight()))
parent.overrideredirect(1)
parent.title(TITLE)
parent.configure(background=BACKROUND_COLOR)
parent.displayFont = tkFont.Font(family=TYPEFACE, size=FONT_SIZE)
self.process_queue()
def process_queue(self):
try:
score = self.queue.get(0)
self.print_message(score)
except Queue.Empty:
pass
self.parent.after(100, self.update_queue)
def update_queue(self):
try:
score = self.queue.get(0)
self.update_message(score)
except Queue.Empty:
pass
self.parent.after(100, self.update_queue)
def print_message(self, messageString):
print 'message', messageString
displayString = SCORE_MESSAGE + str(messageString)
self.message = tk.Message(
self.parent, text=displayString, bg=BACKROUND_COLOR,
font=self.parent.displayFont, fg=TEXT_COLOR, width=TEXTBOX_WIDTH, justify="c")
self.message.place(relx=.5, rely=.5, anchor="c")
def update_message(self, messageString):
print 'message', messageString
displayString = SCORE_MESSAGE + str(messageString)
self.message.config(text=displayString)
def setup_audio(queue, stop_event):
data_in = aa.PCM(aa.PCM_CAPTURE, aa.PCM_NONBLOCK, 'hw:1')
data_in.setchannels(2)
data_in.setrate(44100)
data_in.setformat(aa.PCM_FORMAT_S16_LE)
data_in.setperiodsize(256)
while not stop_event.is_set():
# Read data from device
l, data = data_in.read()
if l:
# catch frame error
try:
max_vol = audioop.rms(data, 2)
scaled_vol = max_vol // 4680
print scaled_vol
if scaled_vol <= 3:
# Too quiet, ignore
continue
queue.put(scaled_vol)
except audioop.error, e:
if e.message != "not a whole number of frames":
raise e
def main():
root = tk.Tk()
queue = Queue.Queue()
window = Display(root, queue)
stop_event = threading.Event()
audio_thread = threading.Thread(target=setup_audio,
args=[queue, stop_event])
audio_thread.start()
try:
root.mainloop()
finally:
stop_event.set()
audio_thread.join()
pass
if __name__ == '__main__':
main()
I don't want to be laying down a new message every time I update. If the .config() doesn't work, is there another method to update the text configuration of the message?
I would use string variables, first create your string variable then set it to want you want it to display at the start next make your object and in text put the sting variable then when you want to change the text in the object change the string variable.
self.messaget = StringVar()
self.messaget.set("")
self.message = tk.Message(
self.parent, textvariable=self.messaget, bg=BACKROUND_COLOR,
font=self.parent.displayFont, fg=TEXT_COLOR,
width=TEXTBOX_WIDTH, justify="c").grid()
#note renember to palce the object after you have created it either using
#.grid(row = , column =) or .pack()
#note that it is textvariable instead of text if you put text instead it will run but
#but will show PY_Var instead of the value of the variable
edit
to change the text without recreating the object you do the name of the string variable you have used and .set
self.messaget.set("hi")
Thanks for your time:
I created a flask server that takes in variables from a form post and outputs a pie or bar graph. While debugging, I noticed this error:
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "C:\Python27\lib\atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "C:\Python27\lib\site-packages\matplotlib\_pylab_helpers.py", line 92, in destroy_all
manager.destroy()
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 618, in destroy
self.canvas._tkcanvas.after_cancel(self.canvas._idle_callback)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 616, in after_cancel
self.tk.call('after', 'cancel', id)
TclError: out of stack space (infinite loop?)
Error in sys.exitfunc:
Traceback (most recent call last):
File "C:\Python27\lib\atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "C:\Python27\lib\site-packages\matplotlib\_pylab_helpers.py", line 92, in destroy_all
manager.destroy()
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 618, in destroy
self.canvas._tkcanvas.after_cancel(self.canvas._idle_callback)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 616, in after_cancel
self.tk.call('after', 'cancel', id)
_tkinter.TclError: out of stack space (infinite loop?)
This seems to cause the server to reload (successfully for what it's worth) which is a problem. No clue what's going on here, other than tkinter being upset. And, no luck with my google fu.
flask server (w debug settings. Mapped vars are due to a project req.):
# Flask App that functions as a graph end point replacement "DAC-780"
# Standard Library
import os
import uuid
# Third Party
from flask import Flask, request
# Local
from pie import make_pie
from bar import make_bar
app_root = os.path.dirname(os.path.abspath(__file__))
images = os.path.join(app_root, 'static/images')
app = Flask(__name__, static_folder="static")
app._static_folder = os.path.join(app_root, 'static')
#app.route('/charts/<path>', methods=['POST'])
def graph(path):
g_data_list = []
file_name = str(uuid.uuid4())
# if bar graph
if path == "chart4.asp":
# grab vars
g_title = str(request.form['Title'])
x_title = str(request.form['CatTitle'])
y_title = str(request.form['ValTitle'])
ser1 = str(request.form['Ser1'])
ser2 = str(request.form['Ser2'])
cat1 = str(request.form['Cat1'])
cat2 = str(request.form['Cat2'])
cat3 = str(request.form['Cat3'])
cat4 = str(request.form['Cat4'])
cat5 = str(request.form['Cat5'])
cat6 = str(request.form['Cat6'])
cat7 = str(request.form['Cat7'])
cat8 = str(request.form['Cat8'])
cat9 = str(request.form['Cat9'])
cat10 = str(request.form['Cat10'])
cat11 = str(request.form['Cat11'])
cat12 = str(request.form['Cat12'])
cat13 = str(request.form['Cat13'])
s1d1 = int(request.form['S1D1'])
s1d2 = int(request.form['S1D2'])
s1d3 = int(request.form['S1D3'])
s1d4 = int(request.form['S1D4'])
s1d5 = int(request.form['S1D5'])
s1d6 = int(request.form['S1D6'])
s1d7 = int(request.form['S1D7'])
s1d8 = int(request.form['S1D8'])
s1d9 = int(request.form['S1D9'])
s1d10 = int(request.form['S1D10'])
s1d11 = int(request.form['S1D11'])
s1d12 = int(request.form['S1D12'])
s1d13 = int(request.form['S1D13'])
s2d1 = int(request.form['S2D1'])
s2d2 = int(request.form['S2D2'])
s2d3 = int(request.form['S2D3'])
s2d4 = int(request.form['S2D4'])
s2d5 = int(request.form['S2D5'])
s2d6 = int(request.form['S2D6'])
s2d7 = int(request.form['S2D7'])
s2d8 = int(request.form['S2D8'])
s2d9 = int(request.form['S2D9'])
s2d10 = int(request.form['S2D10'])
s2d11 = int(request.form['S2D11'])
s2d12 = int(request.form['S2D12'])
s2d13 = int(request.form['S2D13'])
# vars i mapped but weren't needed for my graph lib
g_type = str(request.form['Type'])
g_cats = str(request.form['Cats'])
g_series = str(request.form['Series'])
cat_title = str(request.form['CatTitle'])
# add data to g_data_list so we can process it
g_data_list.append((ser1, [s1d1, s1d2, s1d3, s1d4, s1d5, s1d6, s1d7, s1d8,
s1d9, s1d10, s1d11, s1d12, s1d13]))
g_data_list.append((ser2, [s2d1, s2d2, s2d3, s2d4, s2d5, s2d6, s2d7, s2d8,
s2d9, s2d10, s2d11, s2d12, s2d13]))
x_labels = [cat1, cat2, cat3, cat4, cat5, cat6, cat7, cat8, cat9, cat10,
cat11, cat12, cat13]
# make a graph to return in html
graph = make_bar(g_title, y_title, x_labels, g_data_list, file_name, cat_title, x_title)
else:
# all others are probably pie graphs
g_title = str(request.form['Title'])
cat1 = str(request.form['Cat1'])
cat2 = str(request.form['Cat2'])
cat3 = str(request.form['Cat3'])
cat4 = str(request.form['Cat4'])
s1d1 = int(request.form['S1D1'])
s1d2 = int(request.form['S1D2'])
s1d3 = int(request.form['S1D3'])
s1d4 = int(request.form['S1D4'])
# vars that aren't needed for replications of the final product, but
# were part of the old code
g_type = str(request.form['Type'])
g_cats = str(request.form['Cats'])
g_series = str(request.form['Series'])
cat_title = str(request.form['CatTitle'])
val_title = str(request.form['ValTitle'])
s1 = str(request.form['Ser1'])
s2 = str(request.form['Ser2'])
# add data
g_data_list.append([cat1, s1d1])
g_data_list.append([cat2, s1d2])
g_data_list.append([cat3, s1d3])
g_data_list.append([cat4, s1d4])
# make graph to send back via html
graph = make_pie(g_title, g_data_list, file_name)
# make a web page with graph and return it
html = """
<html>
<head>
<title>%s</title>
</head>
<body>
<img src="/static/images/%s.png" alt="An Error Occured"/>
</body>
</html>
""" % (g_title, str(file_name))
return html
if __name__ == '__main__':
app.run(port=3456, host="0.0.0.0", debug=True)
bar.py:
# creates a bar chart based on input using matplotlib
import os
import numpy as np
import matplotlib.pyplot as plt
from pylab import rcParams
rcParams['figure.figsize'] = 6.55, 3.8
app_root = os.path.dirname(os.path.abspath(__file__))
images = os.path.join(app_root, 'static/images')
def make_bar(g_title, y_title, x_labels, data_series, file_name, cat_title,
x_title):
n_groups = 13
bar_width = 0.35
opacity = 0.4
fig, ax = plt.subplots()
index = np.arange(n_groups)
error_config = {'ecolor': '0.3'}
plt.bar(index, tuple(data_series[0][1]), bar_width,
alpha=opacity,
color='b',
error_kw=error_config,
label='{}'.format(data_series[0][0]))
plt.bar(index + bar_width, tuple(data_series[1][1]), bar_width,
alpha=opacity,
color='r',
error_kw=error_config,
label='{}'.format(data_series[1][0]))
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
plt.xlabel(x_title, fontsize=10)
plt.ylabel(y_title, fontsize=10)
plt.title(g_title, fontsize=11)
plt.xticks(index + bar_width, tuple(x_labels), fontsize=8)
plt.yticks(fontsize=8)
plt.axis('tight')
lgd = plt.legend(fontsize=8, bbox_to_anchor=(1.15, 0.5))
plt.tight_layout()
plt.draw()
plt.savefig('{}/{}.png'.format(images, file_name),
dpi=100, format='png', bbox_extra_artists=(lgd,),
bbox_inches='tight')
return
pie.py:
# creates a pie chart w/ matplotlib
import os
import matplotlib.pyplot as plt
from pylab import rcParams
app_root = os.path.dirname(os.path.abspath(__file__))
images = os.path.join(app_root, 'static/images')
def make_pie(title, g_data_list, file_name):
rcParams['figure.figsize'] = 5.75, 3
labels = [entry[0] for entry in g_data_list]
sizes = [entry[1] for entry in g_data_list]
ax = plt.subplot(111)
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.7, box.height])
patches, texts = ax.pie(sizes, startangle=90)
ax.legend(patches, labels, loc='center left',
bbox_to_anchor=(.9, 0.5), fontsize=8)
plt.axis('equal')
plt.suptitle(g_title, fontsize=12)
plt.draw()
plt.savefig('{}/{}.png'.format(images, file_name), dpi=100, format='png')
return
I noticed that the function that graphed everything, when run separately, would stay running after I closed the plot window. Adding plt.clf() fixed that problem, and appears to be the solution to mine relating to Flask as well.
Had same problem with seaborn
import matplotlib
matplotlib.use('Agg')
helps me.
details: https://matplotlib.org/faq/usage_faq.html#what-is-a-backend
Hi i added a simple GUI in this script
A python script to automatically summarize soccer videos based on the crowd's reactions
The GUI script is the following
from Tkinter import *
from tkFileDialog import askopenfilename
from soccer_reacts import video_edit
class MyFrame(Frame):
def __init__(self):
master = Tk()
Label(master, text="Please Insert Video Path With Browse", width=30).grid(row=0)
Frame.__init__(self)
self.master.title("Video Editor")
self.master.geometry('{}x{}'.format(300, 200))
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
self.button = Button(self, text="Browse", command=self.load_file, width=15)
self.button.grid(row=1, column=0, sticky=W)
self.button2 = Button(self, text="Start", command=self.vid_reactions, width=15)
self.button2.grid(row=2, column=0, sticky=W)
def load_file(self):
fname = askopenfilename(filetypes=(("MP4 files", "*.mp4"),("All files", "*.*") ))
if fname:
self.fname = fname
def vid_reactions(self):
print("[*]Starting operation")
print("[*]File : "+self.fname)
video_edit(self.fname)
print("[*]Operation Finished")
if __name__ == "__main__":
MyFrame().mainloop()
End this is the new code of soccer cuts
import numpy as np # for numerical operations
from moviepy.editor import VideoFileClip, concatenate
def video_edit(file_name):
clip = VideoFileClip(file_name)
cut = lambda i: clip.audio.subclip(i,i+1).to_soundarray(fps=22000)
volume = lambda array: np.sqrt(((1.0*array)**2).mean())
volumes = [volume(cut(i)) for i in range(0,int(clip.audio.duration-2))]
averaged_volumes = np.array([sum(volumes[i:i+10])/10
for i in range(len(volumes)-10)])
increases = np.diff(averaged_volumes)[:-1]>=0
decreases = np.diff(averaged_volumes)[1:]<=0
peaks_times = (increases * decreases).nonzero()[0]
peaks_vols = averaged_volumes[peaks_times]
peaks_times = peaks_times[peaks_vols>np.percentile(peaks_vols,90)]
final_times=[peaks_times[0]]
for t in peaks_times:
if (t - final_times[-1]) < 60:
if averaged_volumes[t] > averaged_volumes[final_times[-1]]:
final_times[-1] = t
else:
final_times.append(t)
final = concatenate([clip.subclip(max(t-5,0),min(t+5, clip.duration))
for t in final_times])
final.to_videofile(file_name) # low quality is the default
When i run the new code, the output is a mp4 file, with the sound of the match
but with no video. I ve checked all the changes i made and i cannot find something wrong. Can anyone help?
I do not why but changing last line from
final.to_videofile(file_name)
to final.write_videofile('The result.mp4')
was a solution