Caffe 抽取CNN网络特征 Python

来源:互联网 发布:asp购物网站源码 编辑:程序博客网 时间:2024/05/26 07:30

Caffe Python特征抽取

转载请注明出处,楼燚(yì)航的blog, 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 npimport matplotlib.pyplot as pltimport osimport caffeimport sysimport pickleimport structimport sys,cv2caffe_root = '../'  # 运行模型的prototxtdeployPrototxt =  '/home/chenjie/baiyan/caffe/models/compcar_model_C_all/deploy_louyihang.prototxt'# 相应载入的modelfilemodelFile = '/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 = 4postfix = '.classify_allCar1716_fc6'# 初始化函数的相关操作def initilize():    print 'initilize ... '    sys.path.insert(0, 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', (2,0,1))    transformer.set_mean('data', np.load(caffe_root + meanFile).mean(1).mean(1)) # mean pixel    transformer.set_raw_scale('data', 255)      transformer.set_channel_swap('data', (2,1,0))      # set net to batch size of 1 如果图片较多就设置合适的batchsize     net.blobs['data'].reshape(1,3,227,227)      #这里根据需要设定,如果网络中不一致,需要调整    num=0    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 +=1        print 'Num ',num,' extract feature ',fea_file        with  open(fea_file,'wb') as f:            for x in xrange(0, net.blobs['fc6'].data.shape[0]):                for y in xrange(0, net.blobs['fc6'].data.shape[1]):                    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[0])     print 'read imageList done image num ', len(imageList)    return imageListif __name__ == "__main__":    net = initilize()    imageList = readImageList(imageListFile)     extractFeature(imageList, net)
0 0
原创粉丝点击