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. lyGrid表格插件

     表格基础参数: grid = lyGrid({           l_column : [{//表格列表数据                 colkey : null,              ...

  2. 谁动了我的timer?——C#的垃圾回收和调试

    先来看如下的一段代码: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 using System; using System.Threading; publi ...

  3. Java中的字符串流的读取和写入(创建文件并判断重复账户)

    各位我又来了!!哎!好心酸!我还没注册到三天!!没法登上博客的首页!!心累!! import java.io.BufferedOutputStream; import java.io.Buffered ...

  4. url传递中文的解决方案

    本文转载:http://www.cnblogs.com/ghd258/archive/2005/10/23/260241.html url传递中文的解决方案 1.设置web.config文件. < ...

  5. java中的泛型(转)

    什么是泛型? 泛型(Generic type 或者 generics)是对 Java 语言的类型系统的一种扩展,以支持创建可以按类型进行参数化的类.可以把类型参数看作是使用参数化类型时指定的类型的一个 ...

  6. ​ScrollView、ListView嵌套

    1.手动设置ListView高度 经过测试发现,在xml中直接指定ListView的高度,是可以解决这个问题的,但是ListView中的数据是可变的,实际高度还需要实际测量.于是手动代码设置ListV ...

  7. java中判断两个字符串是否相等的问题

    我最近刚学java,今天编程的时候就遇到一个棘手的问题,就是关于判断两个字符串是否相等的问题.在编程中,通常比较两个字符串是否相同的表达式是“==”,但在java中不能这么写.在java中,用的是eq ...

  8. Wpf TextChanged事件导致死循环,事件触发循环问题

    1.实例: 说明:当TextBox控件的Text内容发生变化时,TextChanged事件触发,并且会立即同步执行. 基于这个特点,设置一个全局变量标识,ChangeTxtB,如果是正在修改txtB的 ...

  9. eclipse - 自动换行

    eclipse自动换行,设置的感觉不是很好用,可以从这个网址进行更新安装: http://ahtik.com/eclipse-update/

  10. linux list all users.

    cat /etc/passwd sample of list users in linux. ref: Linux Command: List All Users In The System