Last active
March 26, 2019 07:20
-
-
Save cnrblm/f3b2b84e0e43dc66b43a04115f54ce23 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from os import listdir | |
from pickle import dump | |
from keras.applications.vgg16 import VGG16 | |
from keras.preprocessing.image import load_img | |
from keras.preprocessing.image import img_to_array | |
from keras.applications.vgg16 import preprocess_input | |
from keras.models import Model | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument("--n","--name",dest="name", type=str) | |
args = parser.parse_args() | |
if args.name: | |
directory = args.name | |
else: | |
print("-n directory") | |
exit() | |
# extract features from each photo in the directory | |
def extract_features(directory): | |
# load the model | |
model = VGG16() | |
# re-structure the model | |
model.layers.pop() | |
model = Model(inputs=model.inputs, outputs=model.layers[-1].output) | |
# summarize | |
print(model.summary()) | |
# extract features from each photo | |
features = dict() | |
for name in listdir(directory): | |
# load an image from file | |
filename = directory + '/' + name | |
image = load_img(filename, target_size=(224, 224)) | |
# convert the image pixels to a numpy array | |
image = img_to_array(image) | |
# reshape data for the model | |
image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2])) | |
# prepare the image for the VGG model | |
image = preprocess_input(image) | |
# get features | |
feature = model.predict(image, verbose=0) | |
# get image id | |
image_id = name.split('.')[0] | |
# store feature | |
features[image_id] = feature | |
print('>%s' % name) | |
return features | |
# extract features from all images | |
features = extract_features(directory) | |
print('Extracted Features: %d' % len(features)) | |
# save to file | |
dump(features, open('visual_features.pkl', 'wb')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment