-
Notifications
You must be signed in to change notification settings - Fork 3
/
extractor.py
261 lines (220 loc) · 10.1 KB
/
extractor.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
# This file contains functions to define different types of CNNs and extract
# bottleneck features from them given an input image
#
# Copyright: (c) 2019 Paul Hill
"""
Originally, the input images (currently 100x100 samples) were expanded and
interpolated to the input size of the CNN. Now the image is centred using it's
native size within a blank image (full of zeros). This will not affect the
bottleneck characterising features (I think).
Note, the NASNetMobile2 features are 2D and will either need to be flattened.
In the present system, just the central tensor is taken (in order to
characterise the center of the image where the event took place)
"""
from keras.preprocessing import image
from keras.applications.inception_v3 import InceptionV3
from keras.applications.inception_v3 import preprocess_input as inception_v3_preprocessor
from keras.applications.inception_resnet_v2 import InceptionResNetV2
from keras.applications.inception_resnet_v2 import preprocess_input as inception_resnet_v2_preprocessor
from keras.applications.vgg19 import VGG19
from keras.applications.vgg19 import preprocess_input as vgg19_preprocessor
from keras.applications.nasnet import NASNetLarge, NASNetMobile
from keras.applications.nasnet import preprocess_input as nasnet_preprocessor
# from keras.applications.inception_v3 import preprocess_input as inception_v3_preprocessor
from keras.models import Model, load_model, Sequential
from keras.layers import Flatten
from keras.layers.convolutional import Cropping2D
from cifar10vgg import cifar10vgg
from keras import backend as K
K.clear_session()
import numpy as np
class Extractor():
def __init__(self, cnnModel, weights=None):
K.clear_session()
self.cnnModel = cnnModel
self.weights = weights # so we can check elsewhere which model
if weights is None:
if cnnModel == 'InceptionV3':
# Get model with pretrained weights.
base_model = InceptionV3(
weights='imagenet',
include_top=True
)
# We'll extract features at the final pool layer.
self.model = Model(
inputs=base_model.input,
outputs=base_model.get_layer('avg_pool').output
)
self.target_size = (299, 299)
self.preprocess_input = inception_v3_preprocessor
elif cnnModel == 'VGG19':
# Get model with pretrained weights.
base_model = VGG19(
weights='imagenet',
include_top=True
)
# We'll extract features at the final pool layer.
self.model = Model(
inputs=base_model.input,
outputs=base_model.get_layer('fc2').output
)
self.target_size = (224, 224)
self.preprocess_input = vgg19_preprocessor
elif cnnModel == 'InceptionResNetV2':
# Get model with pretrained weights.
base_model = InceptionResNetV2(
weights='imagenet',
include_top=True
)
# We'll extract features at the final pool layer.
self.model = Model(
inputs=base_model.input,
outputs=base_model.get_layer('avg_pool').output
)
self.target_size = (299, 299)
self.preprocess_input = inception_resnet_v2_preprocessor
elif cnnModel == 'NASNetMobile':
# Get model with pretrained weights.
base_model = NASNetMobile(
weights='imagenet',
include_top=True
)
# We'll extract features at the final pool layer.
self.model = Model(
inputs=base_model.input,
outputs=base_model.get_layer('global_average_pooling2d_1').output
)
self.target_size = (224, 224)
self.preprocess_input = nasnet_preprocessor
elif cnnModel == 'NASNetMobileCropTo11':
# Get model with pretrained weights.
base_model = NASNetMobile(
weights='imagenet',
include_top=True
)
# We'll extract features at the final pool layer.
interModel = Model(
inputs=base_model.input,
outputs=base_model.get_layer('activation_188').output
)
self.model = Sequential()
self.model.add(interModel)
self.model.add(Cropping2D(cropping=((3, 3), (3, 3))))
self.model.add(Flatten())
self.target_size = (224, 224)
self.preprocess_input = nasnet_preprocessor
elif cnnModel == 'NASNetMobileCropTo33':
base_model = NASNetMobile(
weights='imagenet',
include_top=True
)
# We'll extract features at the final pool layer.
interModel = Model(
inputs=base_model.get_layer(index=0).input,
outputs=base_model.get_layer(index=-3).output
)
self.model = Sequential()
self.model.add(interModel)
self.model.add(Cropping2D(cropping=((2, 2), (2, 2))))
self.model.add(Flatten())
self.target_size = (224, 224)
self.preprocess_input = nasnet_preprocessor
elif cnnModel == 'NASNetMobileOLD':
# Get model with pretrained weights.
base_model = NASNetMobile(
weights='imagenet',
include_top=False,
pooling='none'
)
self.model = base_model
self.target_size = (224, 224)
self.preprocess_input = nasnet_preprocessor
elif cnnModel == 'NASNetLarge':
# Get model with pretrained weights.
base_model = NASNetLarge(
weights='imagenet',
include_top=True
)
# We'll extract features at the final pool layer.
self.model = Model(
inputs=base_model.input,
outputs=base_model.get_layer('global_average_pooling2d_1').output
)
self.target_size = (331, 331)
self.preprocess_input = nasnet_preprocessor
elif cnnModel == 'cifar10vgg':
base_model = cifar10vgg(False)
interModel = Model(
inputs=base_model.model.input,
# outputs=base_model.model.get_layer('flatten_1').output
outputs=base_model.model.get_layer('max_pooling2d_3').output
# outputs=base_model.model.get_layer('dropout_10').output
# outputs=base_model.model.get_layer('max_pooling2d_3').output
)
self.model = Sequential()
self.model.add(interModel)
self.model.add(Flatten())
self.target_size = (32, 32)
else:
# Load the model first.
self.model = load_model(weights)
# Then remove the top so we get features not predictions.
# From: https://github.com/fchollet/keras/issues/2371
self.model.layers.pop()
self.model.layers.pop() # two pops to get to pool layer
self.model.outputs = [self.model.layers[-1].output]
self.model.output_layers = [self.model.layers[-1]]
self.model.layers[-1].outbound_nodes = []
def normalize_production_here(self, x):
# this function is used to normalize instances in production according to saved training set statistics
# Input: X - a training set
# Output X - a normalized training set according to normalization constants.
# these values produced during first training and are general for the standard cifar10 training set normalization
mean = 120.707
std = 64.15
return (x-mean)/(std+1e-7)
def extract(self, image_path):
if self.cnnModel == 'cifar10vgg':
img = image.load_img(image_path)
x = image.img_to_array(img)
x = self.centeredCrop(x, 32, 32)
x = np.expand_dims(x, axis=0)
# x = self.normalize_production_here(x)
else:
tSize=self.target_size
img = image.load_img(image_path)
x = image.img_to_array(img)
x = self.centerImage(x, tSize[0], tSize[1])
x = np.expand_dims(x, axis=0)
x = self.preprocess_input(x)
# Get the prediction.
features = self.model.predict(x)
if self.weights is None:
# For imagenet/default network:
features = features[0]
else:
# For loaded network:
features = features[0]
return features
def centeredCrop(self, img, new_height, new_width):
# For small CNNs, take the center of the image
width = np.size(img, 1)
height = np.size(img, 0)
left = np.ceil((width - new_width)/2)
top = np.ceil((height - new_height)/2)
right = np.floor((width + new_width)/2)
bottom = np.floor((height + new_height)/2)
cImg = img[int(top):int(bottom), int(left):int(right), :]
return cImg
def centerImage(self, img, new_height, new_width):
# For CNNs using a size larger than the image, just take the image
# put it in the center and pad with zeros.
cImg = np.zeros((new_height, new_width, 3))
width = np.size(img, 1)
height = np.size(img, 0)
left = np.ceil((new_width - width)/2)
top = np.ceil((new_height - height)/2)
right = np.floor((width + new_width)/2)
bottom = np.floor((height + new_height)/2)
cImg[int(top):int(bottom), int(left):int(right), :] = img
return cImg