【问题标题】:Caffe feature extraction is too slow? caffe.Classifier or caffe.NetCaffe特征提取太慢? caffe.Classifier 或 caffe.Net
【发布时间】:2016-04-04 14:38:11
【问题描述】:

我已经用图像训练了一个模型。 现在想将fc-6 特征提取到.npy 文件中。 我正在使用 caffe.set_mode_gpu() 运行 caffe.Classifier 并提取特征。

而不是每帧提取和保存特征。 我将文件夹的所有功能保存到临时变量中,并将完整视频的结果保存到 npy 文件中(减少对磁盘的写入操作次数)。

我还听说我可以使用 Caffe.Net,然后传递一批图像。但我不确定必须进行哪些预处理以及是否更快?

import os
import shutil
import sys
import glob
from multiprocessing import Pool
import numpy as np
import os, sys, getopt
import time


def keep_fldrs(path,listr):
    ll =list()
    for x in listr:
        if os.path.isdir(path+x):
            ll.append(x)
    return ll

def keep_img(path,listr):
    ll = list()
    for x in listr:
        if os.path.isfile(path+str(x)) & str(x).endswith('.jpg'):
            ll.append(x)
    return ll
def ifdir(path):
    if not os.path.isdir(path):
        os.makedirs(path)

# Main path to your caffe installation
caffe_root = '/home/anilil/projects/lstm/lisa-caffe-public/python'

# Model prototxt file
model_prototxt = '/home/anilil/projects/caffe2tensorflow/deploy_singleFrame.prototxt'

# Model caffemodel file
model_trained = '/home/anilil/projects/caffe2tensorflow/snapshots_singleFrame_flow_v2_iter_55000.caffemodel'
sys.path.insert(0, caffe_root)
import caffe
caffe.set_mode_gpu()
net = caffe.Classifier(model_prototxt, model_trained,
                           mean=np.array([128, 128, 128]),
                           channel_swap=(2,1,0),
                           raw_scale=255,
                           image_dims=(255, 255))

Root='/media/anilil/Data/Datasets/UCf_scales/ori_mv_vis/Ori_MV/'
Out_fldr='/media/anilil/Data/Datasets/UCf_scales/ori_mv_vis/feat_fc6/'
allcalsses=keep_fldrs(Root,os.listdir(Root))
for classin in allcalsses:
    temp_class=Root+classin+'/'
    temp_out_class=Out_fldr+classin+'/'
    ifdir(temp_out_class)
    allvids_folders=keep_fldrs(temp_class,os.listdir(temp_class))
    for each_vid_fldr in allvids_folders:
        temp_pres_dir=temp_class+each_vid_fldr+'/'
        temp_out_pres_dir=temp_out_class+each_vid_fldr+'/'
        ifdir(temp_out_pres_dir)
        all_images=keep_img(temp_pres_dir,os.listdir(temp_pres_dir))
        frameno=0
        if os.path.isfile(temp_out_pres_dir+'video.npy'):
            continue
        start = time.time()
        temp_npy= np.ndarray((len(all_images),4096),dtype=np.float32)
        for each_image in all_images:
            input_image = caffe.io.load_image(temp_pres_dir+each_image)
            prediction = net.predict([input_image],oversample=False)
            temp_npy[frameno,:]=net.blobs['fc6'].data[0]
            frameno=frameno+1
        np.save(temp_out_pres_dir+'video.npy',temp_npy)
        end = time.time()
        print "lenght of imgs {} and time taken is {}".format(len(all_images),(end - start))
    print ('Class {} done'.format(classin))

输出

lenght of imgs 426 and time taken is 388.539139032
lenght of imgs 203 and time taken is 185.467905998

每张图像所需的时间现在大约 0.9 秒-

【问题讨论】:

    标签: python numpy optimization caffe pycaffe


    【解决方案1】:

    我在this post.找到了最佳答案

    到现在为止我都用过一个

    net = caffe.Classifier(model_prototxt, model_trained,
                               mean=np.array([128, 128, 128]),
                               channel_swap=(2,1,0),
                               raw_scale=255,
                               image_dims=(255, 255))
    

    初始化模型并获取每个图像的输出。 但这种方法真的很慢,每张图像需要大约 0.9 秒。

    最好的想法是传递一批图像(可能是 100,200,250)变化。取决于您的 GPU 上有多少内存。

    为此,我将caffe.set_mode_gpu() 设置为我有一个,并且当您发送大批量时它会更快。 使用您训练的模型初始化模型。

    net=caffe.Net(model_prototxt,model_trained,caffe.TEST)
    

    创建一个 Transformer 并确保根据您训练模型的方式设置平均值和其他值。

    transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
    transformer.set_transpose('data', (2,0,1)) # height*width*channel -> channel*height*width
    mean_file = np.array([128, 128, 128])
    transformer.set_mean('data', mean_file) #### subtract mean ####
    transformer.set_raw_scale('data', 255) # pixel value range
    transformer.set_channel_swap('data', (2,1,0)) # RGB -> BGR
    data_blob_shape = net.blobs['data'].data.shape
    data_blob_shape = list(data_blob_shape)
    

    读取一组图像并转换为网络输入。

    net.blobs['data'].reshape(len(all_images), data_blob_shape[1], data_blob_shape[2], data_blob_shape[3])
    images = [temp_pres_dir+str(x) for x in all_images]
    net.blobs['data'].data[...] = map(lambda x: 
    transformer.preprocess('data',caffe.io.load_image(x)), images)
    

    通过网络传递这批图像。

    out = net.forward()
    

    您可以随意使用此输出。

    现在每张图像的速度为 20 毫秒

    【讨论】:

    • 请注意“mean_file = np.array([128, 128, 128])”。我认为它是整个数据集的平均图像。
    猜你喜欢
    • 2016-12-13
    • 2018-08-18
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    • 2015-05-24
    • 1970-01-01
    • 2015-05-24
    • 1970-01-01
    相关资源
    最近更新 更多