-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
444 lines (406 loc) · 15.5 KB
/
client.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
import os
import cv2 # THis will import open cv 2
from tkinter import *
import tasks
import collections
import numpy as np
import time
import csv
import requests
import datetime
class File:
"""
Implements all file operation Open Close and Save Files
"""
def __init__(self, path):
self.path = path
def openFile(self, loadType):
"""
This method will open the image
The path for the image comes when a new object is constructed.
THere is a few image open modes:
-1 = cv2.IMREAD_COLOR : Loads a color image. Any transparency of image will be neglected. It is the default flag.
0 = cv2.IMREAD_GRAYSCALE : Loads image in grayscale mode
1 = cv2.IMREAD_UNCHANGED : Loads image as such including alpha channel
"""
self.im = cv2.imread(self.path, loadType)
if self.im == None or self.im.size == 0:
print("Image loaded is empty")
sys.exit(1)
else:
return self.im
def showFile(self):
"""
Does not work in linux need to install some libs
:return:
"""
cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
def saveFile(self, image, dir):
"""
Write the received matrix to a image file on the directory
:return:
"""
print(dir)
path = os.path.split(dir)[0]
print(path)
fileName = os.path.splitext(os.path.split(dir)[1])[0]
print(fileName)
extension = os.path.splitext(dir)[1]
print(extension)
dir = path + "/results/" + fileName + "_processed" + extension
print(dir)
cv2.imwrite(dir, image)
class Handler:
task_ids = {}
results = {}
filename = None
testNumber = 0
def restartData(self):
self.task_ids = {}
self.results = {}
def checkForNoneResults(self, results):
for key, result in results.items():
if not isinstance(result, np.ndarray):
return True
return False
def splitAndSend(self, image, path, algorithm, parameters):
count = 0
for chunk in image:
if len(parameters) == 0:
self.task_ids[count] = algorithm.delay(chunk)
elif len(parameters) == 1:
self.task_ids[count] = algorithm.delay(
chunk, float(parameters.get("parameter1"))
)
elif len(parameters) == 2:
self.task_ids[count] = algorithm.delay(
chunk,
float(parameters.get("parameter1")),
float(parameters.get("parameter2")),
)
elif len(parameters) == 3:
self.task_ids[count] = algorithm.delay(
chunk,
float(parameters.get("parameter1")),
float(parameters.get("parameter2")),
float(parameters.get("parameter3")),
)
self.results[count] = None
count = count + 1
def applyToCompleteImage(self, image, path, algorithm, parameters):
if len(parameters) == 0:
self.task_ids[path] = algorithm.delay(image)
elif len(parameters) == 1:
self.task_ids[path] = algorithm.delay(
image, float(parameters.get("parameter1"))
)
elif len(parameters) == 2:
self.task_ids[path] = algorithm.delay(
image,
float(parameters.get("parameter1")),
float(parameters.get("parameter2")),
)
elif len(parameters) == 3:
self.task_ids[path] = algorithm.delay(
image,
float(parameters.get("parameter1")),
float(parameters.get("parameter2")),
float(parameters.get("parameter3")),
)
self.results[path] = None
def checkProcessingState(self):
self.filename = self.filename + "_" + str(self.testNumber)
self.testNumber += 1
newCSV = GenerateCSV(self.filename)
newCSV.openCSVFile(self.filename)
while self.checkForNoneResults(self.results):
for key, result in self.task_ids.items():
if result.ready():
r = requests.get("http://localhost:5555/api/task/info/" + result.id)
jsonFile = r.json()
if jsonFile["state"] == "SUCCESS":
# print(jsonFile['succeeded'])
# def writeRow(self,taskUID, taskname,receivedTime, startTime, endTime,runtime, whichworker):
newCSV.writeRow(
jsonFile["task-id"],
jsonFile["name"],
jsonFile["received"],
jsonFile["started"],
jsonFile["succeeded"],
jsonFile["runtime"],
jsonFile["worker"],
)
self.results[key] = result.get()
def getSplitResults(self, imageOpen, path):
self.checkProcessingState()
self.results = np.array(
[value for (key, value) in sorted(self.results.items())]
)
imageOpen.saveFile(self.results, path)
def getFolderResults(self, imageOpen):
self.checkProcessingState()
for key, result in self.results.items():
result = np.array(result)
imageOpen.saveFile(result, key)
""" Function to reuse in algorithm application"""
def algorithmApplier(self, algorithm, path, folder, loadType=0, **parameters):
self.filename = algorithm.__name__
imageOpen = File(path)
image = imageOpen.openFile(loadType)
if folder:
self.filename = self.filename + "_allImage"
self.applyToCompleteImage(image, path, algorithm, parameters)
else:
self.filename = self.filename + "_splited"
self.splitAndSend(image, path, algorithm, parameters)
self.getSplitResults(imageOpen, path)
def mainMenu():
"""Function to display Main Menu"""
ans = True
while ans:
print("1. Select spliting algorithm")
print("2. Define an image folder path")
print("9.Exit/Quit")
ans = input("What would you like to do? ")
if ans == "1":
imageType = 0
par1, par2, function, loadType, times = algorithmsMenu(imageType)
singleImage(function, par1, par2, loadType, times)
elif ans == "2":
imageType = 1
par1, par2, function, loadType, times = algorithmsMenu(imageType)
multiImage(function, par1, par2, loadType, times)
elif ans == "9":
print("\n Goodbye")
ans = None
else:
print("\n Not a valid choice! Please try again...")
def algorithmsMenu(imageType):
"""
Selection Menu - Front End Isolation
:return:
"""
ans = True
while ans:
if imageType == 0:
# SINGLE IMAGE
print("1. Edge Detection")
print("2. Thresholding")
print("3. Smooth by Averaging")
print("4. Laplacian Derivative")
print("9. Exit/Quit")
ans = input("What would you like to do? ")
if ans == "1":
ans4 = int(input("Insert number of tests:"))
function = tasks.edgeDetection
return None, None, function, 0, ans4
elif ans == "2":
ans2 = input("Insert threshold value:")
ans3 = input("Insert maximum value:")
ans4 = int(input("Insert number of tests:"))
function = tasks.imageThresholding
return ans2, ans3, function, 0, ans4
elif ans == "3":
ans2 = input("Insert Kernel's X:")
ans3 = input("Insert Kernel's Y:")
ans4 = int(input("Insert number of tests:"))
function = tasks.smoothBy_Averaging
return ans2, ans3, function, -1, ans4
elif ans == "4":
ans1 = int(input("Insert number of tests:"))
function = tasks.laplacianDerivative
return None, None, function, 0, ans1
elif ans == "9":
print("\n Goodbye")
ans = None
return None, None, None
else:
print("\n Not a valid choice! Please try again...")
elif imageType == 1:
# MULTIPLE IMAGES
print("1. Edge Detection")
print("2. Thresholding")
print("3. Rotation")
print("4. Smooth by Averaging")
print("5. Laplacian Derivative")
print("9. Exit/Quit")
ans = input("What would you like to do? ")
if ans == "1":
ans4 = int(input("Insert number of tests:"))
function = tasks.edgeDetection
return None, None, function, 0, ans4
elif ans == "2":
ans2 = input("Insert threshold value:")
ans3 = input("Insert maximum value:")
ans4 = int(input("Insert number of tests:"))
function = tasks.imageThresholding
return ans2, ans3, function, 0, ans4
elif ans == "3":
ans2 = input("Insert angle:")
ans3 = input("Insert scale:")
ans4 = int(input("Insert number of tests:"))
function = tasks.rotation
return ans2, ans3, function, 0, ans4
elif ans == "4":
ans2 = input("Insert Kernel's X:")
ans3 = input("Insert Kernel's Y:")
ans4 = int(input("Insert number of tests:"))
function = tasks.smoothBy_Averaging
return ans2, ans3, function, -1, ans4
elif ans == "5":
ans1 = int(input("Insert number of tests:"))
function = tasks.laplacianDerivative
return None, None, function, 0, ans1
elif ans == "9":
print("\n Goodbye")
ans = None
return None, None, None
else:
print("\n Not a valid choice! Please try again...")
def singleImage(function, par1, par2, loadType, times):
"""
Single image algorithm calls
:param function:
:param par1:
:param par2:
:return:
"""
if par1 is None and par2 is None and function is None:
return
elif par1 is None and par2 is None and function is not None:
imagePath = input("Insert Image Path:")
handler = Handler()
time_elapsed = []
for i in range(times):
begin_time = time.time()
handler.algorithmApplier(function, imagePath, False, loadType)
handler.restartData()
finish_time = time.time()
time_elapsed.append(finish_time - begin_time)
print("Processing Times: " + str(time_elapsed))
print("Mean Processing Time was: " + str(np.mean(time_elapsed)) + " s")
else:
imagePath = input("Insert Image Path:")
time_elapsed = []
handler = Handler()
for i in range(times):
begin_time = time.time()
handler.algorithmApplier(
function, imagePath, False, loadType, parameter1=par1, parameter2=par2
)
handler.restartData()
finish_time = time.time()
time_elapsed.append(finish_time - begin_time)
print("Processing Times: " + str(time_elapsed))
print("Mean Processing Time was: " + str(np.mean(time_elapsed)) + " s")
def multiImage(function, par1, par2, loadType, times):
"""
Multiple image algorithm processing
:return:
"""
if par1 is None and par2 is None and function is None:
return
else:
imagePath = input("Insert Image Folder Path:")
# Making the path an absolute one
fullPathToImage = os.path.abspath(imagePath)
try:
time_elapsed = []
handler = Handler()
for i in range(times):
begin_time = time.time()
aFile = None
for filename in os.listdir(fullPathToImage):
if filename.endswith(".png") or filename.endswith(".jpg"):
if par1 is None and par2 is None and function is not None:
handler.algorithmApplier(
function,
fullPathToImage + "/" + filename,
True,
loadType,
)
else:
handler.algorithmApplier(
function,
fullPathToImage + "/" + filename,
True,
loadType,
parameter1=par1,
parameter2=par2,
)
aFile = fullPathToImage + "/" + filename
else:
print("Can't use this file")
image = File(aFile)
handler.getFolderResults(image)
handler.restartData()
finish_time = time.time()
time_elapsed.append(finish_time - begin_time)
print("Processing Times: " + str(time_elapsed))
print("Mean Processing Time was: " + str(np.mean(time_elapsed)) + " s")
except FileNotFoundError:
print("Check if you entered the right path")
print("The Image Processing has finished")
class GenerateCSV:
"""
Generates a csv file with all the data from the tests
"""
def __init__(self, filename):
"""
Creates the csv and writes the header (Preparing File)
:param name:
"""
with open("./csvFile/" + filename + ".csv", "a", newline="") as fp:
self.timeConversion = timeCls()
self.a = csv.writer(fp, delimiter=",")
self.a.writerow(
[
"TaskUID",
"Task",
"Task Received",
"Task Started",
"Task Succeed",
"Runtime",
"Time Between Reception And Start Processing (s)",
"Processing Time (s)",
"Total Time(s)",
"WorkerName",
]
)
def openCSVFile(self, filename):
"""
Opens a File in append Mode
:param filename:
:return:
"""
self.a = csv.writer(open("./csvFile/" + filename + ".csv", "a"))
def writeRow(
self, taskUID, taskname, receivedTime, startTime, endTime, runtime, whichworker
):
"""
Write a row in the CSV file
"""
self.a.writerow(
[
taskUID,
taskname,
receivedTime,
startTime,
endTime,
runtime,
startTime - receivedTime,
endTime - startTime,
endTime - receivedTime,
whichworker,
]
)
class timeCls:
"""
Time conversion class
"""
def convertTimeStamp(self, timestamp):
return datetime.datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
if __name__ == "__main__":
mainMenu()