-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage_tools.py
572 lines (477 loc) Β· 19.2 KB
/
image_tools.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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
#cython: language_level=3, boundscheck=False
from tools import get_temp_name
# from tools import stdo
# from inspect import currentframe, getframeinfo
# from PIL import Image
import cv2
import numpy as np
from matplotlib import pyplot as plt
import os # For remove or check files
import errno # https://stackoverflow.com/questions/36077266/how-do-i-raise-a-filenotfounderror-properly
import logging
# import time # Delay for camera module
import random
# from time import sleep
logging.getLogger().disabled = True
# https://www.pyimagesearch.com/2015/03/30/accessing-the-raspberry-pi-camera-with-opencv-and-python/
'''
This code is taking an image from the camera and saving it to a file.
- generated by stenography autopilot [ ππ©ββοΈ ]
'''
def take_image(option):
option = option.lower()
if option == ("cam" or "pc"):
"""
Not necessary but may help with PC applications
"""
# https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html
cap = cv2.VideoCapture(0)
# Capture frame-by-frame
# Save the resulting frame to the shared area
success, source_image = cap.read()
if success:
# When everything done, release the capture
cap.release()
else:
logging.error("Camera connection failed.")
return -1
if option == "picam":
# import pdb; pdb.set_trace() # Pi Camera DEBUG
# For take pictures from Raspberry Pi Camera
from picamera.array import PiRGBArray
from picamera import PiCamera
# initialize the camera and grab a reference to the raw camera capture
# ISSUE: https://www.raspberrypi.org/forums/viewtopic.php?t=97188
# camera = PiCamera()
# rawCapture = PiRGBArray(camera)
with PiCamera() as camera:
# camera.capture('image.jpg')
rawCapture = PiRGBArray(camera)
# allow the camera to warmup
# time.sleep(0.1)
# grab an image from the camera
camera.capture(rawCapture, format="bgr")
source_image = rawCapture.array
return source_image
'''
This code is getting all the files in a directory and putting them into a dictionary.
The key of the dictionary is an integer, which will be incremented by 1 each time it runs.
Each value of the dictionary is another dictionary with keys "image", "type", "name" and "path".
These values are set to open_image(file_path, \'cv2grayscale\'), "<class \'numpy.ndarray\'>", "{}".
- generated by stenography autopilot [ ππ©ββοΈ ]
'''
def get_images(path):
from os import listdir
from os.path import isfile, join
only_files = [f for f in listdir(path) if isfile(join(path, f))]
temp_image_list = dict()
i = 0
for file_path in only_files:
file_data = {
"image": open_image(file_path, "cv2-grayscale"),
"type": "<class 'numpy.ndarray'>",
"name": "{}".format(str(file_path)),
"path": "{}".format(path),
}
temp_image_list[i, file_data]
i += 1
return temp_image_list
'''
This code is saving image to the path.
- generated by stenography autopilot [ ππ©ββοΈ ]
'''
def save_image(img, path=None, filename=[], format="png"):
#return
try:
if type(filename) is not list:
logging.exception("filename parameter need to be list of names")
#print("filename parameter need to be list of names")
return -1
if filename == []:
is_get_temp_name = True
else:
is_get_temp_name = False
if path is None or path == "": # If path is empty, then we refer to temp file save protocol
path = "temp_files/"
else:
if path[-1] != "/":
path = path + "/"
"""
dir_list = path.split("/")
directory = ""
for dir in dir_list:
directory += dir + "/"
if not os.path.exists(directory):
os.makedirs(directory, exist_ok=True, mode=0o777)
"""
if not os.path.exists(path):
os.makedirs(path, exist_ok=True, mode=0o777)
if os.path.exists(path):
logging.debug("'{}' Directory directory created.".format(path))
else:
raise IOError
# import pdb; pdb.set_trace()
list_filename = list()
if type(img) is list:
for index, image in enumerate(img):
if is_get_temp_name:
save_filename = get_temp_name()
else:
if filename[index] != "":
save_filename = filename[index]
else:
save_filename = get_temp_name()
#save_path = path + save_filename + "_" + str(index) + "." + format
save_path = path + save_filename + "." + format
list_filename.append(save_filename)
#print("Image will be saved as '{}, {}'".format(save_filename, save_path))
logging.debug("Image will be saved as '{}'".format(save_filename))
cv2.imwrite(save_path, image)
else:
if is_get_temp_name:
save_filename = get_temp_name()
else:
if filename[0] != "":
save_filename = filename[0]
else:
save_filename = get_temp_name()
save_path = path + save_filename + "." + format
logging.debug("Image will be saved as '{}, {}'".format(save_filename, save_path))
#print("Image will be saved as '{}'".format(save_filename), save_path)
cv2.imwrite(save_path, img)
list_filename.append(save_filename)
return path, list_filename
except IOError as error:
logging.exception(
"Directory creation failed, please raport this issue to developer -> {}".format(
error.__str__()
)
)
#print("Directory creation failed, please raport this issue to developer -> {}".format(error.__str__()))
return -1
except Exception as error:
logging.exception(
"An error occurred while save_image function runtime -> " + error.__str__()
)
#print("An error occurred while save_image function runtime -> " + error.__str__())
return -1
return 0
'''
This code is deleting the image from the path.
- generated by stenography autopilot [ ππ©ββοΈ ]
'''
def delete_image(path):
try:
if os.path.exists(path):
os.remove(path)
else:
raise Exception(errno.ENOENT, os.strerror(errno.ENOENT), path)
except Exception as error:
logging.exception(
"An error occurred while delete_image function runtime -> " + error.__str__()
)
return -1
return 0
'''
This code is opening an image and returning it as a numpy array.
- generated by stenography autopilot [ ππ©ββοΈ ]
'''
def open_image(path, option="cv2-grayscale"):
output = "'{}' Image opened with '{}' option.".format(
path.split("/")[-1], option
)
try:
if os.path.exists(path):
if option == "cv2-rgb":
source_image = cv2.imread(
path, cv2.IMREAD_COLOR
) # Read image as colorfull (RGB)
elif option == "cv2-grayscale":
source_image = cv2.imread(
path, cv2.IMREAD_GRAYSCALE
) # Read image as grayscale
else:
logging.error("Option Not Found! -> " + option)
logging.info("Program terminated immediately.")
source_image = np.array([0, 0, 0])
else:
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), path
)
logging.info(output)
except IOError as ioe:
logging.exception("Image Not Found! -> " + ioe.__str__())
source_image = np.array([0, 0, 0])
except FileNotFoundError as fnfe:
logging.exception("File Not Found! -> " + fnfe.__str__())
source_image = np.array([0, 0, 0])
except Exception as error:
logging.exception(
"An error occurred while working in open_image function -> "
+ error.__str__()
)
logging.warning("Program terminated immediately.")
source_image = np.array([0, 0, 0])
return source_image
'''
This code is used to open image with different options.
- generated by stenography autopilot [ ππ©ββοΈ ]
'''
def open_temp_image(path, option, no_cache=True):
output = "'{}' Temprorary image opened with '{}' option.".format(
path.split("/")[-1], option
)
try:
if no_cache:
if option == "cv2-rgb":
return cv2.imread(
path, cv2.IMREAD_COLOR
) # Read image as colorfull (RGB)
elif option == "cv2-grayscale":
return cv2.imread(
path, cv2.IMREAD_GRAYSCALE
) # Read image as grayscale
"""
elif option == "PIL":
source_image = Image.open(path)
elif option == "skimage":
import skimage as ski
source_image = ski.io.imread(path)
"""
else:
logging.error("Option Not Found! -> " + option)
logging.warning("Image open process skipped.")
return -1
logging.info(output)
return 0
else:
"""
This part is still at development.
Aim is store image data in ram with using shared area.
"""
pass
except IOError as ioe:
logging.exception("Image Not Found! -> " + ioe.__str__())
logging.info("Image open process skipped.")
return -1
except FileNotFoundError as fnfe:
logging.exception("File Not Found! -> " + fnfe.__str__())
logging.info("Image open process skipped.")
return -1
except Exception as error:
logging.exception(
"An error occurred while working in open_image function -> "
+ error.__str__()
)
logging.info("Image open process skipped.")
return -1
def show_image(
source,
title=[],
option="plot",
cmap="gray",
open_order=None,
window=True,
event_click=False,
verbose=False,
figsize=(6.4, 4.8)
):
if verbose:
logging.warning("Image will be shown now with title '{}'.".format(title))
if window:
if isinstance(source, (list, tuple)):
'''
This code is creating a figure. Then, it is adding subplots to the figure.
Then, it is showing the image in each subplot and setting title for each of them. Finally, if event_click=True then
it will show an interactive window where user can click on any point of interest (e.g., face). If there are more than one images
in source list then this code will create multiple figures with different number of columns and rows as per open_order parameter.
- generated by stenography autopilot [ ππ©ββοΈ ]
'''
length_of_source_list = len(source)
if open_order is None:
for i in range(0, length_of_source_list):
local_title = []
if i <= len(title):
local_title = [title[i]]
show_image(
source[i], title=local_title, option=option, cmap=cmap, window=window
)
elif open_order > 0:
# https://stackoverflow.com/questions/46615554/how-to-display-multiple-images-in-one-figure-correctly/46616645
figure = plt.figure(figsize=figsize)
columns = open_order
if open_order >= length_of_source_list:
rows = 1
else:
if (length_of_source_list % open_order) > 0:
rows = int(length_of_source_list / open_order) + 1
else:
rows = int(length_of_source_list / open_order)
for i in range(1, length_of_source_list + 1):
figure.add_subplot(rows, columns, i)
if i <= len(title):
plt.title("{}".format(title[i - 1]))
if len(source[i - 1].shape) == 2:
plt.imshow(source[i - 1], cmap=cmap)
else:
plt.imshow(cv2.cvtColor(source[i - 1], cv2.COLOR_BGR2RGB))
click_coordinates = []
if event_click:
def onclick(event, is_verbose=True):
nonlocal click_coordinates
if event.dblclick:
ix, iy = event.xdata, event.ydata
if is_verbose:
logging.info("Choosen: x = %d, y = %d" % (ix, iy))
click_coordinates.append((round(ix), round(iy)))
figure.canvas.mpl_connect("button_press_event", onclick)
plt.show()
return click_coordinates
else:
if option == "cv2":
try:
cv2.namedWindow(title, cv2.WINDOW_NORMAL)
cv2.resizeWindow(title, 600, 600)
cv2.imshow(title, source)
cv2.waitKey()
cv2.destroyAllWindows()
except Exception as error:
logging.error(
"An error occurred while working in show_image function -> "
+ error.__str__()
)
elif option == "plot":
#import matplotlib.pyplot as plt
try:
if title != []:
plt.title("{}".format(title))
if event_click:
figure = plt.figure()
click_coordinates = []
def onclick(event, is_verbose=True):
nonlocal click_coordinates
if event.dblclick:
ix, iy = event.xdata, event.ydata
if is_verbose:
logging.info("Choosen: x = %d, y = %d" % (ix, iy))
click_coordinates.append((round(ix), round(iy)))
figure.canvas.mpl_connect("button_press_event", onclick)
plt.imshow(source, cmap=cmap)
plt.show()
return click_coordinates
except Exception as error:
logging.error(
"An error occurred while working in show_image function -> "
+ error.__str__()
)
else:
logging.warning("Invalid option")
""" # For skimage
plt.imshow(image, cmap='gray', interpolation='nearest')
plt.show()
"""
return 0
'''
This code is converting the image to grayscale.
- generated by stenography autopilot [ ππ©ββοΈ ]
'''
def rgb2gray(img, verbose=False):
try:
if len(img.shape) > 2:
if img.shape[-1] != 1:
if verbose:
logging.info("RGB Image converted to grayscale.")
return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
else:
return img
else:
if verbose:
logging.warning("Image is already grayscale. Returning given image...")
return img
except Exception as error:
logging.exception(
"An error occurred while working in rgb2gray function -> " + error.__str__()
)
return -1
'''
This code is showing two images side by side.
- generated by stenography autopilot [ ππ©ββοΈ ]
'''
def compare2images(img, img2, title="Title"):
logging.info("Images will be shown now with title '{}'.".format(title))
cv2.namedWindow(title, cv2.WINDOW_NORMAL)
try:
cv2.imshow(title, np.hstack([img, img2]))
cv2.waitKey()
cv2.destroyAllWindows()
except Exception as error:
logging.exception(
"An error occurred while working in compare2images function -> "
+ error.__str__(),
)
return 0
'''
This code is checking if the input image is a numpy array. If it\'s not, then we know that the input image was loaded from an external file and therefore needs to be converted into a numpy array before being processed by our model.
- generated by stenography autopilot [ ππ©ββοΈ ]
'''
def is_numpy_image(img):
if type(img) == np.ndarray:
return True
else:
return False
'''
This code is checking if the image is a numpy array. If it isn\'t, then it will convert it to one. Then, we are getting the width and height of the image using `img.shape`. We are also getting the size of the image using `img.size`. Finally, we are printing out all this information in a nice format with some formatting so that everything looks pretty when printed out on screen.
- generated by stenography autopilot [ ππ©ββοΈ ]
'''
def info_image(img):
# option for skimage and numpy image desicion
try:
# https://www.programiz.com/python-programming/methods/built-in/isinstance
output = """Image
|- Width: {0}
|- Height: {1}
|- Size: {2}
'- Type/Class: {3}"""
logging.info(
output.format(
str(img.shape[0]), str(img.shape[1]), str(img.size), str(type(img))
),
)
except Exception as error:
logging.exception(
"An error occurred while working in info_image function -> "
+ error.__str__(),
)
return 0
'''
This code is getting the width, height and fps of a video.
- generated by stenography autopilot [ ππ©ββοΈ ]
'''
def info_video(video, option=""):
# option for skimage and numpy image desicion
try:
# https://www.programiz.com/python-programming/methods/built-in/isinstance
output = """Video
|- Width: {0}
|- Height: {1}
|- FPS: {2}
|- Size: {3}
'- Type/Class: {4}"""
height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) # always 0 in Linux python3
width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) # always 0 in Linux python3
fps = video.get(cv2.CAP_PROP_FPS)
logging.info(
output.format(
str(width),
str(height),
str(fps),
str(width * height),
str(type(video)),
),
)
except Exception as error:
logging.exception(
"An error occurred while working in info_video function -> "
+ error.__str__(),
)
return 0