[多转合成] 使用pycaffe保存各个层的特征图

# coding=utf-8

#python2 caffe_visualize.py

import numpy as np
import matplotlib.pyplot as plt
import os
import sys
sys.path.append("caffe/python")
sys.path.append("caffe/python/caffe")
import caffe

deploy_file_name = 'deploy.prototxt'
model_file_name  = 'net_iter_25000.caffemodel'
test_img   = "src.jpg"
#编写一个函数,用于显示各层的参数,padsize用于设置图片间隔空隙,padval用于调整亮度 
def show_data(data, padsize=1, padval=0, name = 'conv1'):
    #归一化
    data-=data.min()
    data/=data.max()
 
    #根据data中图片数量data.shape[0],计算最后输出时每行每列图片数n
    n = int(np.ceil(np.sqrt(data.shape[0])))
    # padding = ((图片个数维度的padding),(图片高的padding), (图片宽的padding), ....)
    
    #padding = ((0, n ** 2 - data.shape[0]), (0, padsize), (0, padsize)) + ((0, 0),) * (data.ndim - 3)
    #print("data.ndim = {}, data.shape = {}".format(data.ndim,data.shape))
    if data.ndim is 3:
        padding = ((0, n ** 2 - data.shape[0]), (0, padsize), (0, padsize))
        data = np.pad(data, padding, mode='constant', constant_values=(padval, padval))
        # 先将padding后的data分成n*n张图像
        data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))
        # 再将(n, W, n, H)变换成(n*w, n*H)
        data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])
    elif data.ndim is 1:
        data = data.reshape(-1,1)
    plt.set_cmap("gray")
    #plt.imshow(data)
    plt.imsave("caffe_layers/"+name+".jpg",data)
    #plt.axis('off')
 
 
if __name__ == '__main__':
 
    deploy_file = deploy_file_name
    model_file  = model_file_name
    #如果是用了GPU
    #caffe.set_mode_gpu()
 
    #初始化caffe 
    net = caffe.Net(deploy_file, model_file, caffe.TEST)
 
    #数据输入预处理
    # 'data'对应于deploy文件:
    # input: "data"
    transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
 
    # python读取的图片文件格式为H×W×K,需转化为K×H×W
    transformer.set_transpose('data', (2, 0, 1))
 
    # python中将图片存储为[0, 1]
    # 如果模型输入用的是0~255的原始格式,则需要做以下转换
    #transformer.set_raw_scale('data', 255)
    transformer.set_channel_swap('data', (2, 1, 0))
    net.blobs['data'].reshape(1, 3, 300, 300)
    img = caffe.io.load_image(test_img,color=True)
    net.blobs['data'].data[...] = transformer.preprocess('data', img)
    out = net.forward()

    for layer_name, blob in net.blobs.iteritems():
        print("{}\t{}".format(layer_name,str(blob.data.shape)))
        layer_name = layer_name.replace('/','_')
        feature = blob.data.reshape(blob.data.shape[1:])
        show_data(feature, padsize=2, padval=0, name=layer_name)

 需要先在运行目录下新建目录caffe_layers

posted @ 2019-05-08 16:58 aimhabo 阅读(...) 评论(...) 编辑 收藏