-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
64 lines (48 loc) · 1.61 KB
/
utils.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
import os
from PIL import Image
import numpy as np
RESHAPE = (256,256)
def is_an_image_file(filename):
IMAGE_EXTENSIONS = ['.png', '.jpg', '.jpeg']
for ext in IMAGE_EXTENSIONS:
if ext in filename:
return True
return False
def list_image_files(directory):
files = os.listdir(directory)
return [os.path.join(directory, f) for f in files if is_an_image_file(f)]
def load_image(path):
img = Image.open(path)
return img
def preprocess_image(cv_img):
cv_img = cv_img.resize(RESHAPE)
img = np.array(cv_img)
img = (img - 127.5) / 127.5
return img
def deprocess_image(img):
img = img * 127.5 + 127.5
return img.astype('uint8')
def save_image(np_arr, path):
img = np_arr * 127.5 + 127.5
im = Image.fromarray(img)
im.save(path)
def load_images(path, n_images):
if n_images < 0:
n_images = float("inf")
A_paths, B_paths = os.path.join(path, 'A'), os.path.join(path, 'B')
all_A_paths, all_B_paths = list_image_files(A_paths), list_image_files(B_paths)
images_A, images_B = [], []
images_A_paths, images_B_paths = [], []
for path_A, path_B in zip(all_A_paths, all_B_paths):
img_A, img_B = load_image(path_A), load_image(path_B)
images_A.append(preprocess_image(img_A))
images_B.append(preprocess_image(img_B))
images_A_paths.append(path_A)
images_B_paths.append(path_B)
if len(images_A) > n_images - 1: break
return {
'A': np.array(images_A),
'A_paths': np.array(images_A_paths),
'B': np.array(images_B),
'B_paths': np.array(images_B_paths)
}