python调用caffe,执行前向预测
1.搭建环境
编译caffe成功之后,编译python接口:
make pycaffe
同理,编译MATLAB接口:
make matcaffe
2. 代码
这是最简单的前向测试的代码。由于执行的是stereo math的model,所以输入是两张图片
# -*- coding: utf-8 -*- import caffe caffe.set_mode_gpu() #如果不加这条,默认是cpu模式 net = caffe.Net('deploy.prototxt','1.caffemodel',caffe.TEST) #caffe.TEST 设定为测试模式 # 设定图片的shape格式为网络data层格式,img0,img1为输入layer的top transformer1 = caffe.io.Transformer({'Image1': net.blobs['img0'].data.shape}) transformer2 = caffe.io.Transformer({'Image2': net.blobs['img1'].data.shape}) # 改变维度的顺序,由原始的维度(width,height,channel)变成(channel,width,height) transformer1.set_transpose('Image1', (2,0,1)) transformer2.set_transpose('Image2', (2,0,1)) # 交换通道,将图片由RGB变成BGR transformer1.set_channel_swap('Image1', (2,1,0)) transformer2.set_channel_swap('Image2', (2,1,0)) # 加载图片 image1 = caffe.io.load_image('data/0000000-imgL.ppm') image2 = caffe.io.load_image('data/0000000-imgR.ppm') # 执行上面设置的图片预处理操作,并将图片载入到blob中 net.blobs['img0'].data[...] = transformer1.preprocess('Image1',image1) net.blobs['img1'].data[...] = transformer2.preprocess('Image2',image2) # 执行测试 out = net.forward()
还有proto.txt的input layer应该是类似这样子
layer { name: "Image1" type: "Input" top: "img0" input_param { shape: { dim: 1 dim: 3 dim: 540 dim: 960 } } } layer { name: "Image2" type: "Input" top: "img1" input_param { shape: { dim: 1 dim: 3 dim: 540 dim: 960 } } }
参考链接:
http://caffe.berkeleyvision.org/tutorial/interfaces.html;
http://wentaoma.com/2016/08/10/caffe-python-common-api-reference/