# 使用已有模型和训练好的网络
# D:/git/DeepLearning/caffe/test_model.py
# 源自 http://edu.csdn.net/course/detail/3506 视频
import numpy as np;
import sys;
# 指定python接口文件路径
caffe_root='D:/git/DeepLearning/caffe/build/x64/install/';
sys.path.insert(0, caffe_root+'python')
import caffe; # 引入caffepython接口
# 设置设备类型
# caffe_set_mode_cpu(); # 使用cpu
caffe.set_mode_gpu(); # 使用gpu
# 指定使用的最优化网络
model_def = 'models/bvlc_reference_caffenet/deploy.prototxt';
# 指定训练好的模型
model_weights = 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel';
net = caffe.Net(model_def, # defines the structure of the model
model_weights, # contains the trained weights
caffe.TEST) # use test mode (3.g., don't perform dropout)
# create transformer for the input called 'data'
# ilsvrc_2012_mean.npy均值文件,代码库里提供的
mu = np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy');
mu = mu.mean(1).mean(1)
print('mean-subtracted values:', zip('BGR', mu));
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape});
transformer.set_transpose('data', (2,1,0)); # move image channels to outermost dimension
transformer.set_mean('data', mu); # subtract the dataset-mean value in each channel
transformer.set_raw_scale('data', 255); # rescale from [0,1] to [0,255]
transformer.set_channel_swap('data', (2,1,0)); # swap channels from RGB to BGR
net.blobs['data'].reshape(1, # batch size
3, # 3-channel (BGR) images
227, 227); # image size is 227x227
image = caffe.io.load_image('D:/git/DeepLearning/caffe/examples/images/cat.jpg');
transformed_image = transformer.preprocess('data', image);
#copy the image data into the memory allocated for the net
net.blobs['data'].data[...] = transformed_image;
### perform classification
output = net.forward();
# the output probability vector for the first image in the batch
output_prob = output['prob'][0];
print('predicted class is:', output_prob.argmax());
运行结果: