Repository navigation
Expand file tree
/
Copy pathmodelutils.py
More file actions
146 lines (100 loc) · 4.8 KB
/
Copy pathmodelutils.py
File metadata and controls
146 lines (100 loc) · 4.8 KB
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
import numpy as np
import cv2
import tensorflow as tf
def get_session_config(use_gpu=True, dynamic_gpu_memory=True) -> tf.ConfigProto:
# Allow GPU memory growth so tensorflow doesn't allocate all memory
if use_gpu:
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.3
config.gpu_options.allow_growth = dynamic_gpu_memory
else:
config = tf.ConfigProto(device_count={ "GPU": 0 })
return config
def feed_images_batched(model, images_batch: list) -> list:
inputs = {}
for images in images_batch:
# Resize and normalize the images
for key, feed_tensor in model.feed_tensors.items():
assert key in images, "Required input image %s not found in passed images" % key
img = images[key]
shape = feed_tensor.shape
# Resize to target size. This needs to be
# done before potentially expanding the
# channels dimension as it removes it again.
img = cv2.resize(img, tuple(shape[1:3]))
# Make sure we have the channels dimension
# for 1-channel images.
if len(img.shape) == 2:
img = np.expand_dims(img, -1)
assert img.shape == shape[1:], "Shape not equal to target shape, shape: %s target: %s" % (
img.shape, shape[1:])
input_image = img.astype(np.float32) / 255.0
if not key in inputs:
inputs[key] = []
inputs[key].append(input_image)
inference = model(inputs)
# Process all outputs
outputs = []
for _ in range(len(images_batch)):
output_dict = {}
for key in model.fetch_tensors.keys():
output = inference[key][0] * 255.0
# Remove single channel dimension if any
if len(output.shape) == 3 and output.shape[-1] == 1:
output = np.squeeze(output, axis=-1)
output_dict[key] = output
outputs.append(output_dict)
return outputs
def feed_image_batched(model, image_batch: np.ndarray) -> np.ndarray:
assert len(model.feed_tensors) == 1 and len(
model.fetch_tensors) == 1, "Tried to use feed_image with more than one input or output in the model"
input_key = next(iter(model.feed_tensors.keys()))
output_key = next(iter(model.fetch_tensors.keys()))
outputs = feed_images_batched(model, [{input_key: image} for image in image_batch])
return [output[output_key] for output in outputs]
def feed_images(model, images: dict) -> dict:
# Send in all inputs
inputs = {}
# Resize and normalize the images
for key, feed_tensor in model.feed_tensors.items():
assert key in images, "Required input image %s not found in passed images" % key
img = images[key]
shape = feed_tensor.shape
# Resize to target size. This needs to be
# done before potentially expanding the
# channels dimension as it removes it again.
img = cv2.resize(img, tuple(shape[1:3]))
# Make sure we have the channels dimension
# for 1-channel images.
if len(img.shape) == 2:
img = np.expand_dims(img, -1)
assert img.shape == shape[1:], "Shape not equal to target shape, shape: %s target: %s" % (
img.shape, shape[1:])
input_image = img.astype(np.float32) / 255.0
inputs[key] = [input_image]
inference = model(inputs)
# Process all outputs
outputs = {}
for key in model.fetch_tensors.keys():
output = inference[key][0] * 255.0
# Remove single channel dimension if any
if len(output.shape) == 3 and output.shape[-1] == 1:
output = np.squeeze(output, axis=-1)
outputs[key] = output
return outputs
def feed_image(model, image: np.ndarray) -> np.ndarray:
assert len(model.feed_tensors) == 1 and len(
model.fetch_tensors) == 1, "Tried to use feed_image with more than one input or output in the model"
input_key = next(iter(model.feed_tensors.keys()))
output_key = next(iter(model.fetch_tensors.keys()))
outputs = feed_images(model, {input_key: image})
return outputs[output_key]
def load_model(model_path: str, session_config=None):
print("Loading model from", model_path)
model = tf.contrib.predictor.from_saved_model(model_path, config=session_config)
input_keys = ", ".join(model.feed_tensors.keys())
output_keys = ", ".join(model.fetch_tensors.keys())
print("Loaded model with inputs", input_keys, "and outputs", output_keys)
return model
def load_models(model_paths: dict) -> dict:
return {model_name: load_model(model_path) for model_name, model_path in model_paths}