tensorflow---使用训练好的VGG模型加载图片并提取每一层特征

# -*- coding: utf-8 -*-
"""
Created on Sat Feb 16 12:01:19 2019

@author: 

"""

import scipy.io
import numpy as np
import tensorflow as tf
import os
import scipy.misc
import matplotlib.pyplot as plt
#%%
def _conv_layer(_input,_weights,_biases):
    _conv=tf.nn.conv2d(_input,tf.constant(_weights),strides=(1,1,1,1),padding='SAME')
    return tf.nn.bias_add(_conv,_biases)
def _pooling_layer(_input):
    return tf.nn.max_pool(_input,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
def preprocess(image,mean_pixel):
    return image-mean_pixel
def unprocess(image,mean_pixel):
    return image+mean_pixel
def imread(path):
    return scipy.misc.imread(path).astype(np.float)
def imsave(path,img):
    img=np.clip(image,0,255).astype(np.uint8)
    scipy.misc.imsave(path,img)
print("function for VGG ready")
#%%    
def net(data_path,_input_image):
    layers=('conv1_1','relu1_1','conv1_2','relu1_2','pool1',
            'conv2_1','relu2_1','conv2_2','relu2_2','pool2',
            'conv3_1','relu3_1','conv3_2','relu3_2','conv3_3','relu3_3','conv3_4','relu3_4','pool3',
            'conv4_1','relu4_1','conv4_2','relu4_2','conv4_3','relu4_3','conv4_4','relu4_4','pool4',
            'conv5_1','relu5_1','conv5_2','relu5_2','conv5_3','relu5_3','conv5_4','relu5_4'
            )
    data=scipy.io.loadmat(data_path)
    mean=data['normalization'][0][0][0]
    mean_pixel=np.mean(mean,axis=(0,1))
    weights=data['layers'][0]
    net={}
    current=_input_image
    for i,name in enumerate(layers):
        print('i=',i)
        kind=name[:4]
        if kind=='conv':
            kernels,bias=weights[i][0][0][0][0]
            '''
            matconvnet:weights are [width,,height,in_channels,out_channels]
            tensorflow: weights are [height,width,in_channels,out_channels]
            '''
            kernels=np.transpose(kernels,(1,0,2,3))
            bias=bias.reshape(-1)
            current=_conv_layer(current,kernels,bias)
        elif kind=='relu':
            current=tf.nn.relu(current)
        elif kind=='pool':
            current=_pooling_layer(current)
        net[name]=current
    assert len(net)==len(layers)
    return net,mean_pixel,layers
print('network for VGG ready')
            
#%%
cwd=os.getcwd()
VGG_PATH=cwd+'/data/imagenet-vgg-verydeep-19.mat'
IMG_PATH=cwd+'/data/cat1.jpg'
input_image=imread(IMG_PATH)
shape=(1,input_image.shape[0],input_image.shape[1],input_image.shape[2])
image=tf.placeholder('float',shape=shape)
nets,mean_pixel,all_layers=net(VGG_PATH,image)
input_image_pre=np.array([preprocess(input_image,mean_pixel)])
layers=all_layers
#%%
with tf.Session() as sess:
    
    for i,layer in enumerate(layers):
        print('[%d/%d] %s'%(i+1,len(layers),len(layer)))
        features=nets[layer].eval(feed_dict={image:input_image_pre})
        
        print('type of feature is ',type(features))
        print('shape of features is ',features.shape)
        if 1:
            plt.figure(i+1,figsize=(10,5))
            plt.matshow(features[0,:,:,0],cmap=plt.cm.gray,fignum=i+1)
            plt.title(''+layer)
            plt.colorbar()
            plt.show()

  




            
            

 

  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值