1. 程式人生 > >Keras —— 基於Vgg16模型(含全連線層)的圖片識別

Keras —— 基於Vgg16模型(含全連線層)的圖片識別

一、載入並顯示圖片

img_path = 'elephant.jpg'
img = image.load_img(img_path, target_size=(224, 224))
plt.imshow(img)
plt.show()

這裡寫圖片描述

二、圖片預處理

#將圖片轉成numpy array
x = image.img_to_array(img)
#擴充套件維度,因為preprocess_input需要4D的格式
x = np.expand_dims(x, axis=0)
#對張量進行預處理
x = preprocess_input(x)

三、載入VGG16模型(包含全連線層)

model = VGG16(include_top=True, weights='imagenet')
preds = model.predict(x)
# 將結果解碼成一個元組列表(類、描述、概率)(批次中每個樣本的一個這樣的列表)
print('Predicted:', decode_predictions(preds, top=3)[0])

四、預測結果

Predicted: [('n01871265', 'tusker', 0.77154845), ('n02504458', 'African_elephant', 0.15930885), ('n02504013', 'Indian_elephant'
, 0.06914174)]

由預測結果可知,圖片有百分之77的概率是tusker,百分之16的概率是African_elephant,百分之6的概率是Indian_elephant

原始碼地址: