天天看點

VGG19模型,輸入圖像,輸出指定層特征

"""
調用VGG19模型
輸入一張彩色圖像
輸出指定層的特征
VGG19模型的輸入圖像是四維的,但是加載進去的圖像是三維的,是以要提前reshape
指定層的輸出是四維的,是以要reshape到三維
如果要可視化,使用spyder隻能顯示而是圖像
"""

from __future__ import print_function
from keras.preprocessing.image import load_img, save_img, img_to_array
import numpy as np
from scipy.optimize import fmin_l_bfgs_b
import time
import argparse
import matplotlib.image as mpimg # mpimg 用于讀取圖檔
from keras.applications import vgg19
from keras import backend as K
import matplotlib.pyplot as plt
from keras.preprocessing import image
import os
model = vgg19.VGG19(weights='imagenet', include_top=False,)
from keras.models import Model 

#print(model.layers)

img_path ='C:\\Users\\Administrator\\Pictures\\Saved Pictures\\kobe.jpg'
img=image.load_img(img_path)
img=np.array(img)
a,b,c=img.shape
img=img.reshape(1,a,b,c)
#VGG19模型的實際深度是26,本文使用的模型去掉了三個全連接配接層
layer_model=Model(inputs=model.input,outputs=model.layers[20].output)

out=layer_model.predict(img)
print(out.shape)
w,x,y,z=out.shape
out=out.reshape(x,y,z)

plt.imshow(out[:,:,40])
           

指定某一層的的輸出特征圖

VGG19模型,輸入圖像,輸出指定層特征
VGG19模型,輸入圖像,輸出指定層特征

繼續閱讀