Caffe图片特征提取(Python/C++)

Caffe图片特征提取(Python/C++)

1.Caffe特征提取(C++实现)

Caffe框架提供了相应的Tools(build/tools/extract_features.bin)工具extract features,官方教程,使用方法如下:

extract_features.bin xxx.caffemodel xxxx.prototxt layer-name output-path mini-batches db-style

xxx.caffemodel:已训练好的模型参数

xxxx.prototxt :模型定义(包括要提取的图片的路径,mean-file等)

layer_name:要提取的特征的名字(eg. fc6 fc7),中间以空格隔开

output-path:提取的feature保存路径

mini-batches: 每次batch_size的大小

db_-style: feature保存的格式(leveldb/lmdb)

详细内容请参考官方教程,写的很详细。

- 优点:简单,直接可用

- 不足:灵活性不高,需要自己写代码解析相应的feature

2.Caffe特征提取(Python实现)

本文参考了Caffe官方教程feature visualization 的部分代码,利用Python实现了,计算图片均值(mean-file),特征提取及保存,具体过程如下。

1)计算输入图片的均值保存为npy格式。

#**input**
#work_path:working path containing the input file
#list_name:every line containing ‘image_path label‘
#save_name:where to save the mean file
#image_size: the mean_file‘s size
#channel: the mean_file‘s channnel

#**output**
#mean_file value(3*227*227)
def compute_image_mean(work_path,list_name = ‘train.txt‘, save_name = ‘227_227_mean.npy‘, image_size = (227,227), channnel = 3):
    mean = np.zeros((channnel,) + image_size, dtype=np.float64)
    list = os.path.join(work_path,list_name)
    with open(list, ‘r‘) as f:
        lines = f.readlines()
    sample_size = len(lines)
    count = 0
    for i, line in enumerate(lines):
        if(count%1000 == 0):
            print (‘Finish:%d\r\n‘%count)
        image_name, label = line[:-1].split()
        img = cv2.imread(image_name).astype(np.float32)
        res = cv2.resize(img, image_size)
        res = res.transpose(2, 0, 1)
        mean += res
        count += 1
    mean = mean / sample_size
    save_file = os.path.join(work_path,save_name)
    np.save(save_file, mean)
    return mean

2)通过前向传播提取Feature,并保存为npy格式

#**input**
#net:Caffe net
#mean_file:image mean file(c*h*w)
#input_file:input image file(image_path label)
#output_prefix_file(output_path),every image has a output_path
#layer_name:eg. ‘fc6 fc7‘

def computer_features(net,mean_file,input_file,output_prefix_file,
                    layer_names = ‘fc6 fc7‘):
    # load the mean  image  for subtraction
    mu = np.load(mean_file)
    # create transformer for the input called ‘data‘
    transformer = caffe.io.Transformer({‘data‘: net.blobs[‘data‘].data.shape})

    transformer.set_transpose(‘data‘, (2, 0, 1))  # move image channels to outermost dimension
    transformer.set_mean(‘data‘, mu)  # subtract the dataset-mean value in each channel
    transformer.set_raw_scale(‘data‘, 255)  # rescale from [0, 1] to [0, 255]
    transformer.set_channel_swap(‘data‘, (2, 1, 0))  # swap channels from RGB to BGR
    # set the size of the input (we can skip this if we‘re happy
    #  with the default; we can also change it later, e.g., for different batch sizes)
    net.blobs[‘data‘].reshape(batch_size,  # batch size
                              3,  # 3-channel (BGR) images
                              227, 227)  # image size is 227x227

    features = layer_names.split()
    inputlines = []
    outputlines = []
    with open(input_file, ‘r‘) as f:
        for line in f:
            inputlines.append(line)

    with open(output_prefix_file, ‘r‘) as f:
        for line in f:
            outputlines.append(line)

    assert len(inputlines) == len(outputlines)
    i = 0
    for input,output in zip(inputlines,outputlines):
        input = input.strip(‘\n\t‘)
        output = output.strip(‘\n\t‘)
        image_path,label = input.split()
        # print image_path
        input_image = caffe.io.load_image(image_path)
        transformed_image = transformer.preprocess(‘data‘, input_image)
        net.blobs[‘data‘].data[...] = transformed_image
        net.forward()
        if not os.path.isdir(output):
            os.makedirs(output)
        for feature in features:
            output_file = os.path.join(output,feature+‘.npy‘)
            np.save(output_file, net.blobs[feature].data[0])
        if (i%1000 == 0):
            print (‘Finish:%d\r\n‘ % i)
        i += 1
 model_def = ‘models/bvlc_reference_caffenet/deploy.prototxt‘
 model_weights = ‘models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel‘
 net = caffe.Net(model_def,  # defines the structure of the model
                    model_weights,  # contains the trained weights
                    caffe.TEST)  # use test mode (e.g., don‘t perform dropout)
 mean_file = args.root + args.mean
 input_file = args.root + args.inputs
 output_file = args.root + args.outputs
 caffe.set_mode_cpu()
 computer_features(net,mean_file,input_file,output_file)

以上代码每次只处理1张图片,如果数据量较大,会比较慢,建议采用批量的模式来计算,发挥GPU的优势,改动也比较简单,如果需要Batch-size版的,可私下交流。

利用python提取caffe特征最关键的就是:net.blobs[‘fc6’].data,将次参数提取并保存即可

时间: 2024-08-28 18:33:28

Caffe图片特征提取(Python/C++)的相关文章

caffe 图片数据的转换成lmdb和数据集均值(转)

转自网站: http://blog.csdn.net/muyiyushan/article/details/70578077 1.准备数据 使用dog/cat数据集,在训练项目根目录下分别建立train和val文件夹,作为训练数据和验证数据的保存位置.train和val文件夹下各有两个文件夹:dogs和cats,分别保存dog和cat的图片.dog和cat分别有1000张训练图像和400张测试图像. 写一个python脚本文件,遍历train和val两个文件夹,分别生成train.txt和val

使用caffe提供的python接口训练mnist例子

1 首先肯定是安装caffe,并且编译python接口,如果是在windows上,最好把编译出来的python文件夹的caffe文件夹拷贝到anaconda文件夹下面去,这样就有代码自动提示功能,如下: 本文中使用的ide为anaconda安装中自带的spyder,如图所示,将根目录设置为caffe的根目录. import caffe caffe.set_mode_cpu() solver = caffe.SGDSolver('examples/mnist/lenet_solver.protot

RGB值转化图片(python PIL)

今天看到一道misc的题目,得到一RGB值的txt文件,需解决RGB值转图片.具体题目:here 由于第一次碰到这个类型的题目,做一下记录,在这里我采用的是python 的PIL图像库 具体思路: 1.首先我们要先确定图片的size,既宽度高度 通过txt文件行数(61366=2*61*503,因为最后一行是空行,所以不在计算范围内)的整数分解 可以得到以下几个不同的size:503*122,1006*61,30683*2(x,y交换一下对图片不会有很大的变化,只是横着和竖着的区别) 所以我们接

爬取某图片网站多页图片的python爬虫

1. [代码][Python]代码 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 # coding=utf-8 import requests import re from lxml

【泡咖啡1】linux下caffe编译以及python环境配置手记

caffe是一个深度学习的库,相信搞深度学习的话,不是用这个库就是用theano吧.要想使用caffe首先第一步就是要配置好caffe的环境.在这里,我主要说的是在debian的linux环境下如何配置好caffe的库.因为python编写程序比较方便,在文章最后,我还会具体说明如何配置python环境.本文章为本人原创,部分内容整理自网络,若有不妥之处请联系本人删除.非盈利性质网站转载请在文章开头处著名本文作者:77695,来源http://www.cnblogs.com/cj695/.盈利性

百度图片爬虫-python版-如何爬取百度图片?

上一篇我写了如何爬取百度网盘的爬虫,在这里还是重温一下,把链接附上: http://5912119.blog.51cto.com/5902119/1771391 这一篇我想写写如何爬取百度图片的爬虫,这个爬虫也是:搜搜gif(在线制作功能点我) 的爬虫代码,其实爬虫整体框架还是差不多的,但就是会涉及到图片的的一些处理,还是花费了我不少时间的,所以我请阅读的本爬虫的孩子还是认真一些,毕竟程序猿都不容易啊.好的,我也不想多说,爬虫的代码我会分享到去转盘网,想下载本爬虫代码的孩子请点我下载,如果没有下

按照需要分别率长宽比导出图片(python 3)

效率提升的问题 之前朋友需要把大量的图片用分辨率进行区分查找,他说都是打开图片,然后用尺子在屏幕上量......我也是瀑布汗....花的点时间帮他写的小软件,解决这个蛋疼的问题 解决方案 本想用批处理解决,但是考虑到易用性,就用python的tkinter做了简单的界面方便操作. 他也不是程序开发人员,让他安装python环境并不现实,就需要用打包工具处理,网上看到很多用py2exe,看起来有点麻烦,我就直接用pyinstaller打包了,一行代码搞定. 源代码 1 # -*- coding:

CAFFE安装(6):python环境

安装python依赖包 sudo apt-get install python-dev python-pip 首先下载caffe安装包,解压之后进入caffe-master/python目录下执行如下命令 $ for req in $(cat requirements.txt); do pip install $req; done 集成开发环境可以选择Spyder

Caffe初学者第一部:Ubuntu14.04上安装caffe(CPU)+Python的详细过程 (亲测成功, 20180524更新)

前言: 最近在学习深度学习,最先要解决的当然是开源框架的环境安装了.之前一直在学习谷歌的Tensorflow开源框架,最近实验中需要跟别人的算法比较,下载的别人的代码很多都是Caffe的,所以想着搭建好Caffe环境跑别人的代码.这中间经历过很多弯路,开始是入了Ubuntu16.04的坑,很多教程都说GCC版本不匹配,需要降级,我也尝试过发现很多坑:另外,就是安装matlab版本的Caffe以及安装GPU版本的Caffe,都经历了很多的波折,这前后摸索大概花了半个月左右.最后发现Ubuntu14