Caffe Python特征抽取

转载 http://www.cnblogs.com/louyihang-loves-baiyan/

Caffe大家一般用到的深度学习平台都是这个,关于Caffe的训练通常一般都可以通过一些命令来执行,但是在deploy阶段,如果是做实际的工程,那么C++接口用得会相对比较多。但是Caffe是支持Python和Matlab接口的,所以用Python来做一些相关的特征的处理以及额外的任务比较方便

这里我主要是结合了Caffe官网的例程,当然它给的例程是参照的Ipython,然后以命令的形式,我主要做了一些相关的整合。当时也不知道怎么提取一些相关特征,上网一搜也基本上没有干净、好的代码。因此我在这里介绍如何使用Python做特征的抽取。

Python 接口

首先你要确保你已经在安装Caffe时,编译了Python接口,我记得对应着的命令是 make pycaffe,相关的接口是在在Caffe_Root\python目录下,这个目录里面还是有一个caffe模块,提供了一些使用python的基本类

抽取的代码

这里我把其例程中,以及一部分我添加的代码都合到了一起,并且加了注释,希望能对大家有帮助,这里主要是三个函数

  • initialize () 初始化网络的相关
  • readlist() 读取抽取图像列表
  • extractFeatre() 抽取图像的特征,保存为指定的格式

其中在transformer那里需要根据自己的需求设定

import numpy as np
import matplotlib.pyplot as plt
import os
import caffe
import sys
import pickle
import struct
import sys,cv2
caffe_root = '../'
# 运行模型的prototxt
deployPrototxt = '/home/chenjie/baiyan/caffe/models/compcar_model_C_all/deploy_louyihang.prototxt'
# 相应载入的modelfile
modelFile = '/home/chenjie/baiyan/caffe/models/compcar_model_C_all/caffenet_carmodel_baiyan_iter_50000.caffemodel'
# meanfile 也可以用自己生成的
meanFile = 'python/caffe/imagenet/ilsvrc_2012_mean.npy'
# 需要提取的图像列表
imageListFile = '/home/chenjie/DataSet/500CarCNNRetrieve/500CarFaceOrig/images_total.txt'
imageBasePath = '/home/chenjie/DataSet/500CarCNNRetrieve/500CarFaceOrig'
gpuID =
postfix = '.classify_allCar1716_fc6' # 初始化函数的相关操作
def initilize():
print 'initilize ... ' sys.path.insert(, caffe_root + 'python')
caffe.set_mode_gpu()
caffe.set_device(gpuID)
net = caffe.Net(deployPrototxt, modelFile,caffe.TEST)
return net
# 提取特征并保存为相应地文件
def extractFeature(imageList, net):
# 对输入数据做相应地调整如通道、尺寸等等
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
transformer.set_transpose('data', (,,))
transformer.set_mean('data', np.load(caffe_root + meanFile).mean().mean()) # mean pixel
transformer.set_raw_scale('data', )
transformer.set_channel_swap('data', (,,))
# set net to batch size of 如果图片较多就设置合适的batchsize
net.blobs['data'].reshape(,,,) #这里根据需要设定,如果网络中不一致,需要调整
num=
for imagefile in imageList:
imagefile_abs = os.path.join(imageBasePath, imagefile)
print imagefile_abs
net.blobs['data'].data[...] = transformer.preprocess('data', caffe.io.load_image(imagefile_abs))
out = net.forward()
fea_file = imagefile_abs.replace('.jpg',postfix)
num +=
print 'Num ',num,' extract feature ',fea_file
with open(fea_file,'wb') as f:
for x in xrange(, net.blobs['fc6'].data.shape[]):
for y in xrange(, net.blobs['fc6'].data.shape[]):
f.write(struct.pack('f', net.blobs['fc6'].data[x,y])) # 读取文件列表
def readImageList(imageListFile):
imageList = []
with open(imageListFile,'r') as fi:
while(True):
line = fi.readline().strip().split()# every line is a image file name
if not line:
break
imageList.append(line[])
print 'read imageList done image num ', len(imageList)
return imageList if __name__ == "__main__":
net = initilize()
imageList = readImageList(imageListFile)
extractFeature(imageList, net)

还没有尝试,等跑完模型试试特征提取;

Caffe Python特征抽取的更多相关文章

  1. Caffe Python MemoryDataLayer Segmentation Fault

    转载请注明出处,楼燚(yì)航的blog,http://home.cnblogs.com/louyihang-loves-baiyan/ 因为利用Pyhon来做数据的预处理比较方便,因此在data_l ...

  2. Windows7 64下搭建Caffe+python接口环境

    参考链接: http://www.cnblogs.com/yixuan-xu/p/5858595.html http://www.cnblogs.com/zf-blog/p/6139044.html ...

  3. ubuntu16.04+caffe+python接口配置

    在Windows上用了一个学期的caffe了.深感各种不便,于是乎这几天在ubuntu上配置了caffe和它的python接口,现在记录配置过程,亲测可用: 环境:ubuntu16.04 , caff ...

  4. windows配置caffe + python和matlab接口

    参考: http://blog.csdn.net/baidu_26408419/article/details/53711640 http://www.cnblogs.com/love6tao/p/5 ...

  5. win10 caffe python Faster-RCNN训练自己数据集(转)

    一.制作数据集 1. 关于训练的图片 不论你是网上找的图片或者你用别人的数据集,记住一点你的图片不能太小,width和height最好不要小于150.需要是jpeg的图片. 2.制作xml文件 1)L ...

  6. caffe Python API 之中值转换

    # 编写一个函数,将二进制的均值转换为python的均值 def convert_mean(binMean,npyMean): blob = caffe.proto.caffe_pb2.BlobPro ...

  7. caffe Python API 之激活函数ReLU

    import sys import os sys.path.append("/projects/caffe-ssd/python") import caffe net = caff ...

  8. caffe Python API 之 数据输入层(Data,ImageData,HDF5Data)

    import sys sys.path.append('/projects/caffe-ssd/python') import caffe4 net = caffe.NetSpec() 一.Image ...

  9. caffe python 接口设置

    安装编译完成后, 运行 cd sudogedit  ~/.bashrc 在打开的文件末尾加入 export PYTHONPATH=/home/caffe-master/python:$PYTHONPA ...

随机推荐

  1. poj1323

    题目大意: 预测游戏 假如有MR人,包括你自己,玩一个特殊的卡片游戏,开始的时候,没有参与者接收到N张卡片,这pip卡片是一个正整数最少M*N,没有两张pip卡片是一样的,在一圈后,每个玩家选择一张卡 ...

  2. UVA 10820 - Send a Table 数论 (欧拉函数)

    Send a Table Input: Standard Input Output: Standard Output When participating in programming contest ...

  3. Appium移动自动化测试(一)--安装Appium(转)

    Appium移动自动化测试(一)--安装Appium 2015-05-30 17:48 by 虫师, 70668 阅读, 13 评论, 收藏, 编辑 Appium 自动化测试是很早之前就想学习和研究的 ...

  4. Linux开发工具之gcc

    一.gcc入门(上)   1.gcc相关概念   gcc(GNU C Compiler)编译器,最初支持C语言,现已支持C.C++.Java.Pascal.Ada.COBOL语言等:支持多种硬件平台: ...

  5. Directory类

    string[] pathes = Directory.GetDirectories(@"G:\ReawFiles");//获得所有的文件夹 string[] pathes = D ...

  6. HTTP 状态响应码 意思详解/大全

    HTTP 状态响应码 意思详解/大全 转:http://blog.csdn.net/helin916012530/article/details/29842595 HTTP状态码(HTTP Statu ...

  7. 我是怎样自学日语的(太TM励志了!)

    学日语并不难,难是难在你有没有信心学好日语,有没有恒心学好日语.如果三天打鱼两天晒网的话,我劝你还是趁早死心,在语言世界里没有任何的捷径,有的只是艰辛和不懈的努力. 我自认为自己在学语言方面很有天赋, ...

  8. Ajax的原理和运行机制

    关于ajax,是最近炒得非常火的一种技术,并且时下它也是非常流行.当然,它并不是什么新技术,而是在各种已有的技术和支持机制下的一个统一.在我的项目中,偶尔也会用到ajax,用来给用户一些无刷新的体验. ...

  9. ASP.Net MVC4排序检索分页的实现

    前言 上一节我们做到了如下的一个基础查询页面.本节我们向这个页面中加入排序.搜索和分页功能. 排序 从上图中的地址栏中可以看到这个页面调用的是Company Controller下的Index Act ...

  10. 让 IE6/7/8 也支持HTML5标签的方式

    方式一:引入Google的HTML5.js线上文件 <!–[if lt IE9]> <script src="http://html5shiv.googlecode.com ...