#参考1:https://blog.csdn.net/sushiqian/article/details/78614133
#参考2:https://blog.csdn.net/thy_2014/article/details/51659300
#coding=utf-8
importnumpy as npimportmatplotlib.pyplot as pltimportosimportsyssys.path.append("/home/wit/caffe/python")
sys.path.append("/home/wit/caffe/python/caffe")importcaffedeploy_file_name= '/home/wit/wjx/MobileNetSSD_deploy.prototxt'model_file_name= '/home/wit/wjx/mobilenet_iter_25000.caffemodel'test_img= "/home/wit/wjx/src.jpg"
#编写一个函数,用于显示各层的参数,padsize用于设置图片间隔空隙,padval用于调整亮度
def show_data(data, padsize=1, padval=0, name = 'conv0'):#归一化
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)
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:])
plt.set_cmap('gray')
plt.imshow(data)
plt.imsave(name+'.jpg',data)
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)#caffe中图片是BGR格式,而原始格式是RGB,所以要转化
transformer.set_channel_swap('data', (2, 1, 0))#将输入图片格式转化为合适格式(与deploy文件相同)
net.blobs['data'].reshape(1, 3, 300, 300)#读取图片
#参数color: True(default)是彩色图,False是灰度图
img = caffe.io.load_image(test_img,color=True)#数据输入、预处理
net.blobs['data'].data[...] = transformer.preprocess('data', img)#前向迭代,即分类
out =net.forward()#输出结果为各个可能分类的概率分布(deploy中最后一层)
predicts = out['detection_out']print "Prob:"
printpredicts
#最可能分类
predict =predicts.argmax()print "Result:"
printpredictfor layer_name, blob innet.blobs.iteritems():print layer_name + '\t' +str(blob.data.shape)#---------------------------- 显示特征图 -------------------------------
feature = net.blobs['conv1'].dataprint(feature.shape)
feature= feature.reshape(64,150,150)
show_data(feature, padsize=2, padval=0, name='conv1')