经常因为在不同的语言中调用caffe而四处查找资料,在此将常用的接口记录一下,便于查阅与更新
MatCaffe用法总结 http://blog.csdn.net/zackzhaoyang/article/details/51043318
1、matlab调用caffe
caffe.reset_all();
clear; close all;clc;
%% settings
folder = './';
model = [folder 'CNN_deploy.prototxt'];
weights = [folder 'CNN_iter_15000000.caffemodel'];
%% load model using mat_caffe
net = caffe.Net(model,weights,'test');
%% read test image and forward
im = imread('c7.jpg');
im = im2double(im);
input_data = { im };
out = net.forward(input_data);
%% show net parameter and data details
修改每层的数据,比如可以把参数乘以10:
net.params('conv1', 1).set_data(net.params('conv1', 1).get_data() * 10);
% set weights
net.params('conv1', 2).set_data(net.params('conv1', 2).get_data() * 10);
% set bias
layer_name='conv1'
2、python调用caffe
import caffe
import cv2
import numpy as np
import matplotlib.pyplot as plt
#For pyplot to be stable
from pylab import *
#If GPU is not available
caffe.set_mode_cpu()
#Define the net
model = 'CNN_deploy.prototxt';
weights = 'CNN_iter_15000000.caffemodel';
net = caffe.Net(model,weights,caffe.TEST)
#read image and pre-process
input_file = 'c7.jpg'
im = caffe.io.load_image(input_file)#读取图片
im = cv2.cvtColor(im , cv2.COLOR_RGB2YCR_CB)
im = np.copy(im [:,:,0]);
(h,w) = img.shape
c = 1
input = np.reshape(img, (h,w,c))
#Change the data shape of the Net and transform data
net.blobs['data'].reshape(1,c,h,w)
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
#transformer.set_mean('data', np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy').mean(1).mean(1))
transformer.set_transpose('data', (2,0,1))
#transformer.set_channel_swap('data', (2,1,0))
#transformer.set_raw_scale('data', raw_scale)
#forward net and get an output
out = net.forward_all(data=np.asarray([transformer.preprocess('data', input )]))
#show net parameter and data details
print('params:')
for k, v in net.params.items():
print ('weight:',k, v[0].data.shape)
print ('b:',k, v[1].data.shape)
print('data:')
for k, v in net.blobs.items():
print (k, v.data.shape)