# [多转合成] 使用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"
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 = ((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 = 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)