如何安装caffe的caffe python接口安装

#如何使用pycaffe接口#之利用caffe模型来识别图像
Classification: Instant Recognition with Caffe
this example we'll classify an image with the bundled CaffeNet
model (which is based on the network architecture of Krizhevsky et
al. for ImageNet).
We'll compare CPU and GPU modes and then dig into the model to
inspect features and the output.
First, set up
Python,&numpy,
and&matplotlib.
# set up Python environment: numpy for numerical routines, and matplotlib for plotting
import numpy as np
import matplotlib.pyplot as plt
# display plots in this notebook
%matplotlib inline
# set display defaults
plt.rcParams['figure.figsize'] = (10, 10)
# large images
plt.rcParams['image.interpolation'] = 'nearest'
# don't interpolate: show square pixels
plt.rcParams['image.cmap'] = 'gray'
# use grayscale output rather than a (potentially misleading) color heatmap
Load&caffe.
# The caffe module needs to be on the P
we'll add it here explicitly.
import sys
caffe_root = '../'
# this file should be run from {caffe_root}/examples (otherwise change this line)
sys.path.insert(0, caffe_root + 'python')
import caffe
# If you get "No module named _caffe", either you have not built pycaffe or you have the wrong path.
If needed, download the
reference model ("CaffeNet", a variant of AlexNet).
if os.path.isfile(caffe_root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'):
print 'CaffeNet found.'
print 'Downloading pre-trained CaffeNet model...'
!../scripts/download_model_binary.py ../models/bvlc_reference_caffenet
CaffeNet found.
2. Load net and set up input preprocessing
Set Caffe to CPU mode and load
the net from disk.
caffe.set_mode_cpu()
model_def = caffe_root + 'models/bvlc_reference_caffenet/deploy.prototxt'
model_weights = caffe_root + '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 (e.g., don't perform dropout)
Set up input preprocessing. (We'll use Caffe's&caffe.io.Transformer&to
do this, but this step is independent of other parts of Caffe, so
any custom preprocessing code may be used).
Our default CaffeNet is configured to take images in BGR format.
Values are expected to start in the range [0, 255] and then have
the mean ImageNet pixel value subtracted from them. In addition,
the channel dimension is expected as the first (outermost)
dimension.
matplotlib will load images with values in the range [0, 1] in RGB
format with the channel as the&innermost&dimension,
we are arranging for the needed transformations here.
# load the mean ImageNet image (as distributed with Caffe) for subtraction
mu = np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy')
mu = mu.mean(1).mean(1)
# average over pixels to obtain the mean (BGR) pixel values
print 'mean-subtracted values:', zip('BGR', mu)
# create transformer for the input called 'data'
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
transformer.set_transpose('data', (2,0,1))
# 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
mean-subtracted values: [('B', 104.9), ('G', 116.67), ('R', 122.6)]
3. CPU classification
Now we're ready to perform
classification. Even though we'll only classify one image, we'll
set a batch size of 50 to demonstrate batching.
# set the size of the input (we can skip this if we're happy
# we can also change it later, e.g., for different batch sizes)
net.blobs['data'].reshape(50,
# batch size
# 3-channel (BGR) images
# image size is 227x227
Load an image (that comes with
Caffe) and perform the preprocessing we've set up.
image = caffe.io.load_image(caffe_root + 'examples/images/cat.jpg')
transformed_image = transformer.preprocess('data', image)
plt.imshow(image)
Adorable! Let's classify
# copy the image data into the memory allocated for the net
net.blobs['data'].data[...] = transformed_image
### perform classification
output = net.forward()
output_prob = output['prob'][0]
# the output probability vector for the first image in the batch
print 'predicted class is:', output_prob.argmax()
predicted class is: 281
The net gives us a vector of
the most probable class was the 281st one. But is
that correct? Let's check the ImageNet labels...
# load ImageNet labels
labels_file = caffe_root + 'data/ilsvrc12/synset_words.txt'
if not os.path.exists(labels_file):
!../data/ilsvrc12/get_ilsvrc_aux.sh
labels = np.loadtxt(labels_file, str, delimiter='\t')
print 'output label:', labels[output_prob.argmax()]
output label: n tabby, tabby cat
"Tabby cat" is correct! But
let's also look at other top (but less confident predictions).
# sort top five predictions from softmax output
top_inds = output_prob.argsort()[::-1][:5]
# reverse sort and take five largest items
print 'probabilities and labels:'
zip(output_prob[top_inds], labels[top_inds])
probabilities and labels:
[(0., 'n tabby, tabby cat'),
(0.2379719, 'n tiger cat'),
(0., 'n Egyptian cat'),
(0., 'n red fox, Vulpes vulpes'),
(0., 'n lynx, catamount')]
We see that less confident
predictions are sensible.
4. Switching to GPU mode
Let's see how long
classification took, and compare it to GPU mode.
%timeit net.forward()
1 loop, best of 3: 1.42 s per loop
That's a while, even for a batch
of 50 images. Let's switch to GPU mode.
caffe.set_device(0)
# if we have multiple GPUs, pick the first one
caffe.set_mode_gpu()
net.forward()
# run once before timing to set up memory
%timeit net.forward()
10 loops, best of 3: 70.2 ms per loop
That should be much faster!
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。1.安装python:
yum install python-devel.x86_64
2.Makefile.config修改
WITH_PYTHON_LAYER := 1 #取消注释
3.安装python依赖
如果安装& Python可以免去下面步骤
cd $CAFFE_ROOT/python
for req in $(cat requirements.txt); do pip install $ done
make clean
make pycaffe -j32
make test -j32
&5. 使Caffe的python接口永久生效
vim /etc/profile
profile最后添加: export PYTHONPATH=/root/$CAFFE_ROOT/python:$PYTHONPATH
source /etc/profile
有一些python库没有安装,在import caffe测试时会出错,常见的库缺失错误:
ImportError: No module named skimage.io
ImportError:& No module named scipy
ImportError:& No module named google.protobuf.internal
yum install python-matplotlib.x86_64
pip install -U scikit-imagepip install scipyeasy_install protobuf
安装完成上述caffe依赖的python库后,可能需要重新执行一遍第4,5步操作。
阅读(...) 评论()君,已阅读到文档的结尾了呢~~
本篇是对前面第5个读书笔记的一个补充。讲一下在python界面上分类的一些细节。
扫扫二维码,随身浏览文档
手机或平板扫扫即可继续访问
caffe学习笔记6 在python界面上用训练好的Imagenet模型去分类图形-薛开宇
举报该文档为侵权文档。
举报该文档含有违规或不良信息。
反馈该文档无法正常浏览。
举报该文档为重复文档。
推荐理由:
将文档分享至:
分享完整地址
文档地址:
粘贴到BBS或博客
flash地址:
支持嵌入FLASH地址的网站使用
html代码:
&embed src='/DocinViewer-4.swf' width='100%' height='600' type=application/x-shockwave-flash ALLOWFULLSCREEN='true' ALLOWSCRIPTACCESS='always'&&/embed&
450px*300px480px*400px650px*490px
支持嵌入HTML代码的网站使用
您的内容已经提交成功
您所提交的内容需要审核后才能发布,请您等待!
3秒自动关闭窗口你的浏览器禁用了JavaScript, 请开启后刷新浏览器获得更好的体验!
python版本3.5.2
按照清单安装接口依赖包的时候报错如下
总是提示这三行错误
ImportError: No module named 'ConfigParser'
dpkg: 处理软件包 cython (--configure)时出错:
子进程 已安装 post-installation 脚本 返回错误状态 1
请问要怎么解决?
建议使用python2.7版本的。sudo apt-get update
sudo apt-get install python-pip python-dev python-numpy
sudo apt-get install gfortran
sudo pip install -r ${CAFFE_ROOT}/python/requirements.txt
sudo apt-get install graphviz
sudo pip install pydot
要回复问题请先或
关注: 2 人

我要回帖

更多关于 caffe的python接口 的文章

 

随机推荐