-
Notifications
You must be signed in to change notification settings - Fork 2
/
image_util.py
48 lines (32 loc) · 1.16 KB
/
image_util.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
import os
import pickle
import keras
def get_features(DIR):
# Load Model
model = keras.applications.VGG16()
# Re-structure model
model.layers.pop()
model = keras.models.Model(inputs=model.inputs, outputs=model.layers[-1].output)
# Summary
print(model.summary())
# Extract features from images
features = dict()
for image_name in os.listdir(DIR):
file_name = DIR + '/' + image_name
image = keras.preprocessing.image.load_img(file_name, target_size=(224, 224))
image = keras.preprocessing.image.img_to_array(image)
image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
image = keras.applications.vgg16.preprocess_input(image)
# Get the features data by putting the image through the model
feature = model.predict(image, verbose=0)
# Image ID
image_id = image_name.split('.')[0]
features[image_id] = feature
print(image_name)
return features
def main():
DIR = 'data/Flicker8k_Dataset'
features = get_features(DIR)
pickle.dump(features, open('data/features.pkl', 'wb'))
if __name__ == "__main__":
main()