26
37

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

KERASで学習済みのモデルをロードして画像1枚を判別

Last updated at Posted at 2018-11-03

そこら中に似たようなスクリプトがあると思いますが
忘れないように自分用メモ

#想定のモデル
以前作ったコレなので、ラベル名は某アニメのキャラクター5名・・・

#確認環境
 python3.6.6
 Tensorflow:1.10.0
 Keras:2.2.2

#スクリプト全体


from keras.models import load_model
import numpy as np
from keras.preprocessing.image import img_to_array, load_img

jpg_name = '識別したい画像ファイル名'
model_file_name='重みモデルのファイル名'

model=load_model('./フォルダ名/' + model_file_name+'.h5')

img_path = ('./フォルダ名/' + jpg_name + '.jpg')
img = img_to_array(load_img(img_path, target_size=(224,224)))
img_nad = img_to_array(img)/255
img_nad = img_nad[None, ...]
    
label=['homura','kyoko','madoka','mami','sayaka']
pred = model.predict(img_nad, batch_size=1, verbose=0)
score = np.max(pred)
pred_label = label[np.argmax(pred[0])]
print('name:',pred_label)
print('score:',score)

#解説
一応解説を・・・

#import

from keras.models import load_model
import numpy as np
from keras.preprocessing.image import img_to_array, load_img

#データ読込

#ファイル名
jpg_name = '識別したい画像ファイル名'
model_file_name='重みモデルのファイル名'

#学習済みモデルの読込
model=load_model('./フォルダ名/' + model_file_name+'.h5')

#画像の読込
img_path = ('./フォルダ名/' + jpg_name + '.jpg')
img = img_to_array(load_img(img_path, target_size=(224,224)))
#0-1に変換
img_nad = img_to_array(img)/255
#4次元配列に
img_nad = img_nad[None, ...]

#判別と表示


#表示したいクラス名(任意設定)
label=['homura','kyoko','madoka','mami','sayaka']
#判別
pred = model.predict(img_nad, batch_size=1, verbose=0)
#判別結果で最も高い数値を抜き出し
score = np.max(pred)
#判別結果の配列から最も高いところを抜きだし、そのクラス名をpred_labelへ
pred_label = label[np.argmax(pred[0])]
#表示
print('name:',pred_label)
print('score:',score)
26
37
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
37

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?