分享好友 人工智能首页 频道列表

Caffe 抽取CNN网络特征 Python

Caffe教程  2023-02-09 16:318340

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 = 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)

查看更多关于【Caffe教程】的文章

展开全文
相关推荐
反对 0
举报 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
caffe调试 ubuntu1404+eclipse
转自:http://blog.csdn.net/yaoxingfu72/article/details/47999795首先确保你caffe编译成功,而且makefile.config中将DEBUG:=1那一行取消注释,我的caffe根目录为 caffe-master。你也可以在Eclipse中编译caffe,我是先编译好caffe,然后进入Eclipse中调试1

0评论2023-03-08522

Caffe hdf5 layer data 大于2G 的导入
问题:      Datatype class: H5T_FLOAT,      Check failed: error == cudaSuccess (2 vs. 0)  out of memory.      hdf5 layer 最大的导入的大小是2G, 超过会报错[1]。解决方法:     有人 h5repart -m1g 将数据集分割成多个文件每个是

0评论2023-02-10987

caffe神经网络中不同的lr_policy间的区别
lr_policy可以设置为下面这些值,相应的学习率的计算为:- fixed:   保持base_lr不变.- step:    如果设置为step,则还需要设置一个stepsize,  返回 base_lr * gamma ^ (floor(iter / stepsize)),其中iter表示当前的迭代次数- exp:     返回base_lr

0评论2023-02-10949

Ubuntu配置GPU+CUDA+CAFFE ubuntu配置dns
参考网站:http://blog.csdn.net/xizero00/article/details/43227019/ (主要参考)http://www.cnblogs.com/platero/p/3993877.html (caffe+cudaGPU)http://www.cnblogs.com/platero/p/4118139.html (cuDNN)http://developer.download.nvidia.com/compute/cuda/

0评论2023-02-10616

关于深度学习(deep learning)的常见疑问 --- 谷歌大脑科学家 Caffe缔造者 贾扬清
问答环节问:在finetuning的时候,新问题的图像大小不同于pretraining的图像大小,只能缩放到同样的大小吗?” 答:对的:)问:目前dl在时序序列分析中的进展如何?研究思路如何,能简单描述一下么答:这个有点长,可以看看google最近的一系列machine trans

0评论2023-02-10646

深度学习框架Caffe —— Deep learning in Practice
因工作交接需要, 要将caffe使用方法及整体结构描述清楚。 鉴于也有同学问过我相关内容, 决定在本文中写个简单的tutorial, 方便大家参考。 本文简单的讲几个事情:Caffe能做什么?为什么选择caffe?环境整体结构Protocol buffer训练基本流程Python中训练Debu

0评论2023-02-09598

使用caffe的HDF5数据完毕回归任务
    一直在研究怎样用caffe做行人检測问题。然而參考那些经典结构比方faster-rcnn等,都是自己定义的caffe层来完毕的检測任务。这些都要求对caffe框架有一定程度的了解。近期看到了怎样用caffe完毕回归的任务,就想把检測问题当成回归问题来解决。   

0评论2023-02-09943

Caffe 编译: undefined reference to imencode()
本系列文章由 @yhl_leo 出品,转载请注明出处。 文章链接:http://blog.csdn.net/yhl_leo/article/details/52150781 整理之前编译工程中遇到的一个Bug,贴上提示log信息:...CXX/LD -o .build_release/examples/siamese/convert_mnist_siamese_data.bin.build

0评论2023-02-09884

[caffe]caffe资料收集 Caffeine.
1.caffe主页,有各种tutorial。2.Evan Shelhamer的tutorial,包括视频。 

0评论2023-02-09776

caffe_ssd学习-用自己的数据做训练 ssd caffe
几乎没用过linux操作系统,不懂shell编程,linux下shell+windows下UltraEdit勉勉强强生成了train.txt和val.txt期间各种错误辛酸不表,照着examples/imagenet/readme勉勉强强用自己的数据,按imagenet的训练方法,把reference_caffenet训起来了,小笔记本的风

0评论2023-02-09664

caffe Python API 之中值转换
# 编写一个函数,将二进制的均值转换为python的均值def convert_mean(binMean,npyMean):blob = caffe.proto.caffe_pb2.BlobProto()bin_mean = open(binMean, 'rb' ).read()blob.ParseFromString(bin_mean)arr = np.array( caffe.io.blobproto_to_array(blob)

0评论2023-02-09843

Windows10安装ubuntu & caffe GPU版
1.Ubuntu https://www.cnblogs.com/EasonJim/p/7112413.htmlhttps://blog.csdn.net/jesse_mx/article/details/61425361 安装后启动不了,直接进入windows.解决方案:https://www.cnblogs.com/lymboy/p/7783756.htmlhttps://jingyan.baidu.com/article/5553fa

0评论2023-02-091018

更多推荐