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. 《Web 前端面试指南》2、JavaScript 的 Bind 函数进阶

    使用 Bind() 设置方法中 this 对象 //<button>获取随机的人</button>​ //<input type="text"> ...

  2. es6小技巧

    let myKey = 'variableKey'; let obj = { key1: 'One', key2: 'Two', [myKey]: 'Three' /* 棒呆! */ }; 给变量键加 ...

  3. 排序(5)---------高速排序(C语言实现)

    继shell发明了shell排序过后呢,各位计算机界的大牛们又開始不爽了,为什么他能发明.我就不能发明呢.于是又有个哥们蹦出来了.哎...那么多排序,就木有一个排序是中国人发明的.顺便吐槽一下,一百年 ...

  4. Git客户端(Windows系统)的使用

    本文环境: 操作系统:Windows XP SP3 Git客户端:TortoiseGit-1.8.5.0-32bit 一.安装Git客户端 全部安装均采用默认! 1. 安装支撑软件 msysgit:  ...

  5. 《火球——UML大战需求分析》(第1章 大话UML)——1.2 结构型的UML(Structure Diagram)

    说明: <火球——UML大战需求分析>是我撰写的一本关于需求分析及UML方面的书,我将会在CSDN上为大家分享前面几章的内容,总字数在几万以上,图片有数十张.欢迎你按文章的序号顺序阅读,谢 ...

  6. 【iOS】3D Touch

    文章内容来源于Apple的开发者文档:https://developer.apple.com/library/content/documentation/UserExperience/Conceptu ...

  7. Tomcat中Listener的使用范例(转载http://cywhoyi.iteye.com/blog/2075848)

    Tomcat是非常有名的开源容器,因其开源我们可以对其做定制化的改变,而且Tomcat在其配置文件方面做了很多注释说明摘要,帮助我们更好的定制化我们所需的功能点. New Tomcat Listene ...

  8. 【开源java游戏框架libgdx专题】-13-开发工具-地图的使用

    支持libGDX的地图编辑器有很多种,其中比较常用的工具为Tiled地图工具.Tiled是一款非常好用的地图编辑器.下载地址:http://www.mapeditor.org TiledMap类: 又 ...

  9. 用js生成二维码

    <!doctype html> <html> <meta charset="utf-8"/> <head> <script s ...

  10. response.setContentType()的作用及参数

    package com.java1234.util; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse ...