python接口调用已训练好的caffe模型测试分类方法

yipeiwu_com6年前Python基础

训练好了model后,可以通过python调用caffe的模型,然后进行模型测试的输出。

本次测试主要依靠的模型是在caffe模型里面自带训练好的结构参数:~/caffe/models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel,以及结构参数

:~/caffe/models/bvlc_reference_caffenet/deploy.prototxt相结合,用python接口进行调用。

训练的源代码以及相应的注释如下所示:

# -*- coding: UTF-8 -*-
import os
import caffe
import numpy as np
root='/home/zf/caffe/'#指定根目录
deploy=root+'models/bvlc_reference_caffenet/deploy.prototxt'#结构文件
caffe_model=root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'
#已经训练好的model
 
dir =root+'examples/images/'#保存测试图片的集合
filelist=[]
filenames=os.listdir(dir)
for fn in filenames:
  fullfilename = os.path.join(dir,fn)
  filelist.append(fullfilename)
#filelist.append(fn)
def Test(img):
#加载模型
  net = caffe.Net(deploy,caffe_model,caffe.TEST)
 
# 加载输入和配置预处理
  transformer = caffe.io.Transformer({'data':net.blobs['data'].data.shape})
  transformer.set_mean('data', np.load('/home/zf/caffe/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', 255.0)
 
#注意可以调节预处理批次的大小
#由于是处理一张图片,所以把原来的10张的批次改为1
  net.blobs['data'].reshape(1,3,227,227)
 
#加载图片到数据层
  im = caffe.io.load_image(img)
  net.blobs['data'].data[...] = transformer.preprocess('data', im)
 
#前向计算
  out = net.forward()
 
# 其他可能的形式 : out = net.forward_all(data=np.asarray([transformer.preprocess('data', im)]))
 
#预测分类
  print out['prob'].argmax()
 
#打印预测标签
  labels = np.loadtxt("/home/zf/caffe/data/ilsvrc12/synset_words.txt", str, delimiter='\t')
  top_k = net.blobs['prob'].data[0].flatten().argsort()[-1]
  print 'the class is:',labels[top_k]
  f=file("/home/zhengfeng/caffe/examples/zf/label.txt","a")
  f.writelines(img+' '+labels[top_k]+'\n')
labels_filename=root +'data/ilsvrc12/synset_words.txt'
#循环遍历文件夹root+'examples/images/'下的所有图片
for i in range(0,len(filelist)):
  img=filelist[i]
  Test(img)

ps:主要有以下的文件需要说明

待测试的文件夹里面的图片数据为:

最后的输出结果如下:

以下是本人定义的label.txt文件写入的预测的数据:

如果在编译的时候出现import caffe error的话,说明没有导入caffe

Export PYTHONPATH=$PYTHONPATH:/home/zf/caffe/python,如果还是不行,可能是你的caffe的python接口未编译,cd /home/zf/caffe,然后执行make pycaffe,接着再测试。

以上这篇python接口调用已训练好的caffe模型测试分类方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python错误处理详解

在程序运行的过程中,如果发生了错误,可以事先约定返回一个错误代码,这样,就可以知道是否有错,以及出错的原因。在操作系统提供的调用中,返回错误码非常常见。比如打开文件的函数open(),成...

Python判断telnet通不通的实例

这个跟ping那个差不多,ping的那个脚本就是通过这个改了下,大体一致,不过telnet的不需要判断返回的字符串。快一些 这里具体需要telnet的ip是需要自己向定义好的数组中写的...

python去掉 unicode 字符串前面的u方法

有时我们会碰到类似下面这样的 unicode 字符串: u'\xe4\xbd\xa0\xe5\xa5\xbd' 这明显不是一个正确的 unicode 字符串,可能是在哪个地方转码转...

Python调用C++,通过Pybind11制作Python接口

我是在ubuntu系统进行实验的,所以和window可能会有区别。 python调用C/C++有不少的方法,如boost.python, swig, ctypes, pybind11等,...

python 网络编程常用代码段

python 网络编程常用代码段

服务器端代码: # -*- coding: cp936 -*- import socket sock = socket.socket(socket.AF_INET, socket....