-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
231 lines (180 loc) · 8.94 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# This the implementation of ModelB
# This model learns the errors associated with the annotated frams
import pandas as pd
import numpy as np
import cv2
import os
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.utils import plot_model
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Flatten
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import concatenate
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from matplotlib import pyplot
from PIL import Image, ImageDraw
import matplotlib.pyplot as plt
import math
from numpy.random import seed
seed(1)
from models import batch_training
from models import create_models
from models import global_params
from models import stripping_edges
from utils import yoloTracker
from main import *
from flask import Flask, request, render_template, jsonify
# app = Flask()
app = Flask(__name__, template_folder="templates")
ABSOLUTE_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'workdir')
frame_path = ABSOLUTE_PATH+'/'+FRAMES_PATH+'/'
yolo_coor_path = ABSOLUTE_PATH+'/'+YOLO_OUTPUT_TRACKED_PATH+'/'
modelB_coor_path = ABSOLUTE_PATH+'/'+MODEL_B_OUTPUT_PATH+'/'
human_coor_path = ABSOLUTE_PATH+'/'+FINAL_UI_OUTPUT_PATH+'/'
class Server:
def __init__(self):
super().__init__()
self.right_model = None
self.left_model = None
self.top_model = None
self.bottom_model = None
def retrain_model(self, side_name, image_path, yolo_coor, human_coor):
print("Retrain mode - Start")
#read the original frame
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# scale pixel values to [0, 1]
image = image.astype('float32')
strips = stripping_edges.strip(image, yolo_coor[1], yolo_coor[0], yolo_coor[3], yolo_coor[2]) #args: img, xmin, ymin, xmax, ymax
strips[0] /= 255.0
strips[1] /= 255.0
strips[2] /= 255.0
strips[3] /= 255.0
# checkpoint
es = EarlyStopping(monitor='mae', mode='min', patience=10, restore_best_weights=True, verbose=1)
if(side_name == 'bottom'):
bottom_part = cv2.resize(strips[1], (MODEL_HEIGHT, MODEL_WIDTH))
self.bottom_model.fit(np.array([bottom_part]), np.array([human_coor[2]-yolo_coor[2]]), epochs=10, callbacks=[es])
elif(side_name == 'left'):
left_part = cv2.resize(strips[2], (MODEL_HEIGHT, MODEL_WIDTH))
self.left_model.fit(np.array([left_part]), np.array([human_coor[1]-yolo_coor[1]]), epochs=10, callbacks=[es])
elif(side_name == 'top'):
top_part = cv2.resize(strips[3], (MODEL_HEIGHT, MODEL_WIDTH))
self.top_model.fit(np.array([top_part]), np.array([human_coor[0]-yolo_coor[0]]), epochs=10, callbacks=[es])
else: #right side
right_part = cv2.resize(strips[0], (MODEL_HEIGHT, MODEL_WIDTH))
self.right_model.fit(np.array([right_part]), np.array([human_coor[3]-yolo_coor[3]]), epochs=10, callbacks=[es])
print("Retrain mode - Over")
def fix_errors(self, image_path, yolo_coor, modelB_coor, human_coor): #[ymin xmin ymax xmax]
print("Fixing errors - Start")
#check for bottom side
if(abs(modelB_coor[2] - human_coor[2]) >= 3): #modelB wrongly predicts
self.retrain_model('bottom', image_path, yolo_coor, human_coor)
#check for left side
if(abs(modelB_coor[1] - human_coor[1]) >= 3): #modelB wrongly predicts
self.retrain_model('left', image_path, yolo_coor, human_coor)
#check for top side
if(abs(modelB_coor[0] - human_coor[0]) >= 3): #modelB wrongly predicts
self.retrain_model('top', image_path, yolo_coor, human_coor)
#check for right side
if(abs(modelB_coor[3] - human_coor[3]) >= 3): #modelB wrongly predicts
self.retrain_model('right', image_path, yolo_coor, human_coor)
print("Fixing errors - Over")
def modelB_prediction(self, image_path, yolo_coor, next_modelB_path):
predictions = [0, 0, 0, 0]
#read the original frame
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# scale pixel values to [0, 1]
image = image.astype('float32')
# image /= 255.0
strips = stripping_edges.strip(image, yolo_coor[1], yolo_coor[0], yolo_coor[3], yolo_coor[2]) #args: img, xmin, ymin, xmax, ymax
strips[0] /= 255.0
strips[1] /= 255.0
strips[2] /= 255.0
strips[3] /= 255.0
#right side
right_part = cv2.resize(strips[0], (MODEL_HEIGHT, MODEL_WIDTH))
right_pre = self.right_model.predict([[right_part]])
predictions[3] = yolo_coor[3]+right_pre[0][0]
#bottom side
bottom_part = cv2.resize(strips[1], (MODEL_HEIGHT, MODEL_WIDTH))
bottom_pre = self.bottom_model.predict([[bottom_part]])
predictions[2] = yolo_coor[2]+bottom_pre[0][0]
#left side
left_part = cv2.resize(strips[2], (MODEL_HEIGHT, MODEL_WIDTH))
left_pre = self.left_model.predict([[left_part]])
predictions[1] = yolo_coor[1]+left_pre[0][0]
#top side
top_part = cv2.resize(strips[3], (MODEL_HEIGHT, MODEL_WIDTH))
top_pre = self.top_model.predict([[top_part]])
predictions[0] = yolo_coor[0]+top_pre[0][0]
predictions = list(map(int, predictions))
# write the modelB predictions to modelB prediction folder
with open(next_modelB_path, 'w') as new_file:
new_file.write('car '+' '.join(map(str, predictions))+'\n')
def createBaseModels(self):
self.right_model = batch_training.batch_train('right')
self.bottom_model = batch_training.batch_train('bottom')
self.left_model = batch_training.batch_train('left')
self.top_model = batch_training.batch_train('top')
return
server = Server()
@app.route("/")
def home():
return render_template('form.html')
@app.route("/trigger", methods=['POST'])
def triggerAPI():
if request.method == 'POST':
# try:
request_data = request.get_json()
frame_number = request_data['frame_number']
frame_filename = request_data['frame_filename']
print(frame_number, frame_filename)
# frame_number = int(request.form['frame_number'])
# frame_filename = request.form['frame_filename']
if(frame_number == 1):
yolo_next_frame = yoloTracker.trackNextObject(0, frame_filename)
yolo_next_frame = yoloTracker.trackNextObject(frame_number, frame_filename)
if (frame_number < BATCH_SIZE):
helper.copy_file_to(yolo_next_frame, modelB_coor_path + yolo_next_frame.split("\\")[-1])
if(frame_number >= BATCH_SIZE):
# Image path
# yolo coor
# modelB coor
# human coor
cur_image_path = frame_path+'frame-' + str(frame_number).zfill(3) + '.jpg'
next_image_path = frame_path+'frame-' + str(frame_number+1).zfill(3) + '.jpg'
cur_yolo_path = yolo_coor_path+frame_filename
next_yolo_path = yoloTracker.getFilesPathAsList(yolo_coor_path)[int(frame_number)]
cur_modelB_path = modelB_coor_path+frame_filename
next_modelB_path = modelB_coor_path+'\\'+next_yolo_path.split('\\')[-1]
cur_human_path = human_coor_path+frame_filename
cur_yolo_coor = list(map(float, open(cur_yolo_path, 'r').readline().split()[1:])) #[ymin xmin ymax xmax]
next_yolo_coor = list(map(float, open(next_yolo_path, 'r').readline().split()[1:]))
cur_modelB_coor = list(map(float, open(cur_modelB_path, 'r').readline().split()[1:]))
cur_human_coor = list(map(float, open(cur_human_path, 'r').readline().split()[1:]))
if (frame_number == BATCH_SIZE):
# createYOLOTracker(frame_filename)
server.createBaseModels()
# return {'message': "32=Success"}
else:
server.fix_errors(cur_image_path, cur_yolo_coor, cur_modelB_coor, cur_human_coor)
server.modelB_prediction(next_image_path, next_yolo_coor, next_modelB_path)
return {'message': ">=32-Success"}
else:
return {'message': "<32-Success"}
# except Exception as e:
# print("Error: ", e)
# return {'message': "Error"}
return {'message': "GET-Success"}
if (__name__=='__main__'):
app.run(debug=False, threaded=False)