KerasによるVGG-16を用いた画像分類

最終更新: 2017-03-20 15:40

KerasによるVGG-16を用いた画像分類

コード

from keras.applications.vgg16 import VGG16, preprocess_input, decode_predictions
from keras.preprocessing import image
import numpy as np
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('image')
args = parser.parse_args()

model = VGG16(weights='imagenet')

img = image.load_img(args.image, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
preds = model.predict(preprocess_input(x))
results = decode_predictions(preds, top=5)[0]
for result in results:
    print('Probability {:.2f}% => [{}]'.format(result[2]*100., result[1]))

実行例

$ python vgg16.py elephants.jpg 
Probability 54.06% => [African_elephant]
Probability 44.08% => [tusker]
Probability 1.87% => [Indian_elephant]
Probability 0.00% => [bison]
Probability 0.00% => [water_buffalo]

注意事項

参考ページ