1. 程式人生 > >批量提取 caffe 特徵 (python, C++, Matlab)(待續)

批量提取 caffe 特徵 (python, C++, Matlab)(待續)

本文參考如下

關於如何批量提取特徵,本文的框架如下:
1. 準備資料及相應準備工作
2. 初始化網路
3.讀取影象列表
4.提取影象特徵,並儲存為特定格式

Python方法一
主要有三個函式:
initialize () 初始化網路的相關
readlist() 讀取抽取影象列表
extractFeatre() 抽取影象的特徵,儲存為指定的格式

其中在transformer那裡需要根據自己的需求設定

#encoding:utf-8
#詳情請檢視http://www.cnblogs.com/louyihang-loves-baiyan/p/5078746.html
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/bids/caffe/caffe-master/changmiao/model/deploy.prototxt' # 相應載入的modelfile modelFile = '/home/bids/caffe/caffe-master/changmiao/model/bvlc_reference_caffenet.caffemodel'
# meanfile 也可以用自己生成的 meanFile = 'python/caffe/imagenet/ilsvrc_2012_mean.npy' # 需要提取的影象列表 imageListFile = '/home/bids/caffe/caffe-master/changmiao/data/temp.txt' imageBasePath = '/home/bids/caffe/caffe-master/changmiao/data/cat' #gpuID = 4 #根據你自己電腦的GPU情況而定 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 #imageList = os.listdir(imageBasePath) 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)