Caffe python feature Extraction

Source: Internet
Author: User

Caffe python feature extraction reprint http://www.cnblogs.com/louyihang-loves-baiyan/

Caffe we generally use the deep learning platform is this, about Caffe training usually can be carried out by some commands, but in the Deploy phase, if the actual project, then the C + + interface will be relatively more. But Caffe is a python and Matlab interface, so it's easy to use Python for some related features and extra tasks.

Here I mainly combine the Caffe official website of the routine, of course, it gives the example of Ipython, and then in the form of command, I mainly do a number of related integration. At that time also do not know how to extract some of the relevant features, Internet search also basically no clean, good code. So I'm here to show you how to use Python for feature extraction.

Python interface

First you have to make sure that you have compiled the Python interface when you install Caffe, and I remember that the corresponding command is make pycaffe that the relevant interface is in the Caffe_Root\python directory, and there is a Caffe module in the directory, which provides some basic classes of Python.

The extracted code

Here I put in its routines, as well as some of the code I added together, and added comments, I hope to be helpful, here is mainly three functions

    • Initialize () Initialization of network related
    • ReadList () reading a list of extracted images
    • Extractfeatre () Extracts the characteristics of an image and saves it in a specified format

Where the transformer needs to be set according to its own needs.

Import NumPy asNpimport Matplotlib.pyplot aspltimport osimport caffeimport sysimport pickleimportstructImport Sys,cv2caffe_root='.. /'# Prototxtdeployprototxt running the model='/home/chenjie/baiyan/caffe/models/compcar_model_c_all/deploy_louyihang.prototxt'# The corresponding modelfilemodelfile loaded='/home/chenjie/baiyan/caffe/models/compcar_model_c_all/caffenet_carmodel_baiyan_iter_50000.caffemodel'# meanfile can also be created with your own meanfile='Python/caffe/imagenet/ilsvrc_2012_mean.npy'# The list of images that need to be extracted imagelistfile='/home/chenjie/dataset/500carcnnretrieve/500carfaceorig/images_total.txt'Imagebasepath='/home/chenjie/dataset/500carcnnretrieve/500carfaceorig'Gpuid=4postfix='. Classify_allcar1716_fc6'# initialization function related Operation 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)returnNet # Extract features and save them as corresponding files Def extractfeature (imageList, net): # Adjust input data accordingly such as channel, size, etc. 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))      # SetNET to batch size of1If the picture is more, set the appropriate batchsize net.blobs['Data'].reshape (1,3,227,227) #这里根据需要设定, if the network is inconsistent, you need to adjust num=0     forImageFileinchImagelist: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+=1Print'Num'Num'Extract Feature', fea_file with open (Fea_file,'WB') asF: forXinchXrange0, net.blobs['Fc6'].data.shape[0]):                 forYinchXrange0, net.blobs['Fc6'].data.shape[1]): F.write (struct. Pack ('F', net.blobs['Fc6'].data[x,y]) # Read file list def readimagelist (imagelistfile): ImageList=[] with open (Imagelistfile,'R') asfi: while(True): Line= Fi.readline (). Strip (). Split () # Every line isa image file nameifNot line : BreakImagelist.append (line[0]) Print'read imageList done image num', Len (imageList)returnimageListif__name__ = ="__main__": Net=initilize () imageList=readimagelist (imagelistfile) extractfeature (imageList, net)


Have not tried, and so on after running the model to try feature extraction;

Caffe python feature Extraction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.