在matlab和python中调用caffe的方法

经常因为在不同的语言中调用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'

nth_layer_para = net.layer_vec(net.name2layer_index(layer_name));% show parameter
nth_layer_para_data = nth_layer_para.params(1).get_data(); % weights
nth_layer_data = net.blob_vec(net.name2layer_index(layer_name)-1);% show data
nth_layer_data_data = nth_layer_data.get_data();


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)


猜你喜欢

转载自blog.csdn.net/eagelangel/article/details/52412068