Caffe 抽取CNN網絡特征 Python


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 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 = 4
postfix = '.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 imageList

if __name__ == "__main__":
    net = initilize()
    imageList = readImageList(imageListFile) 
    extractFeature(imageList, net)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM