# 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_layerspython