forked from jacobgil/keras-cam
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpreprocessing.py
50 lines (42 loc) · 1.72 KB
/
preprocessing.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
import numpy as np
from scipy.misc import imread
from scipy.misc import imresize
VGG_16_IMAGE_SHAPE = (224, 224)
def preprocess_image_batch(image_paths, crop_size=None, color_mode='rgb',
out=None):
"""
Consistent preprocessing of images batches
:param image_paths: iterable: images to process
:param crop_size: tuple: crop images if specified
:param img_size: tuple: resize images if specified
:param color_mode: Use rgb or change to bgr mode based on type of model you want to use
:param out: append output to this iterable if specified
"""
img_list = []
img_size = VGG_16_IMAGE_SHAPE
for im_path in image_paths:
img = imread(im_path, mode='RGB')
if img_size:
img = imresize(img, img_size)
img = img.astype('float32')
# We normalize the colors (in RGB space) with the empirical means on the training set
img[:, :, 0] -= 123.68
img[:, :, 1] -= 116.779
img[:, :, 2] -= 103.939
# We permute the colors to get them in the BGR order
if color_mode == 'bgr':
img[:, :, [0, 1, 2]] = img[:, :, [2, 1, 0]]
img = img.transpose((2, 0, 1))
if crop_size:
img = img[:, (img_size[0] - crop_size[0]) // 2:(img_size[0] + crop_size[0]) // 2
, (img_size[1] - crop_size[1]) // 2:(img_size[1] + crop_size[1]) // 2]
img_list.append(img)
try:
img_batch = np.stack(img_list, axis=0)
except:
raise ValueError('when img_size and crop_size are None, images'
' in image_paths must have the same shapes.')
if out is not None and hasattr(out, 'append'):
out.append(img_batch)
else:
return img_batch