zoukankan      html  css  js  c++  java
  • Caffe2(3)----下载现成的模型并使用

    Caffe2训练好的模型可在Model Zoo下载,下载的命令很简单,接下来以下载和使用squeezenet为例,进行简单说明。

    1.浏览可下载的模型

    已有模型都放在github上,地址:https://github.com/caffe2/caffe2/wiki/Model-Zoo,当前有caffe和caffe2两种版本的选择。

    2.选择下载模型

    注意名字为小写,有些会加下划线,我们这里选择caffe2的版本

    下载并安装(安装目录为/usr/local/caffe2/python/models),命令如下:

    python -m caffe2.python.models.download --install squeezenet

    有时候需要sudo的权限,则要改为执行如下命令:

    sudo PYTHONPATH=/usr/local python -m caffe2.python.models.download --install squeezenet

    3.应用模型

    我们尝试从网上下载一些代码,然后进行预测,在官方代码的基础上做了一些改动,代码如下:

    # load up the caffe2 workspace
    from caffe2.python import workspace
    # choose your model here (use the downloader first)
    from caffe2.python.models import squeezenet as mynet
    # helper image processing functions
    import caffe2.python.tutorials.helpers as helpers
    
    import skimage.io 
    from matplotlib import pyplot as plt
    
    # load the pre-trained model
    init_net = mynet.init_net
    predict_net = mynet.predict_net
    # you must name it something
    predict_net.name = "squeezenet_predict"
    workspace.RunNetOnce(init_net)
    workspace.CreateNet(predict_net)
    p = workspace.Predictor(init_net.SerializeToString(), predict_net.SerializeToString())
    
    # use whatever image you want (local files or urls)
    #img_pth = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/7b/Orange-Whole-%26-Split.jpg/1200px-Orange-Whole-%26-Split.jpg"
    #img_pth = "https://upload.wikimedia.org/wikipedia/commons/a/ac/Pretzel.jpg"
    img_pth = "https://cdn.pixabay.com/photo/2015/02/10/21/28/flower-631765_1280.jpg"
    # average mean to subtract from the image
    mean = 128
    # the size of images that the model was trained with
    input_size = 227
    
    # use the image helper to load the image and convert it to NCHW
    img = helpers.loadToNCHW(img_pth, mean, input_size)
    
    # submit the image to net and get a tensor of results
    
    results = p.run([img])
    response = helpers.parseResults(results)
    # and lookup our result from the list
    print response
    
    #show result on image
    img_mat = skimage.io.imread(img_pth)
    skimage.io.imshow(img_mat)
    plt.title(response,{'fontsize': '20'})
    plt.savefig('pretzel.jpg')
    plt.show()

    注意别忘记把推理的文件inference_codes.txt放在程序的当前目录

    4.结果

    对三张图片分类的结果及其概率如图所示

    5.参考资料

    [1].Model Zoo Doc

    [2].Model Zoo Github

    [3].贾扬清等人撰文详解Caffe2:从强大新能力到上手教程

  • 相关阅读:
    jdk安装
    ubuntu 搜狗输入法成功安装
    matlab load
    matlab save 命令
    数字信号处理的思考
    非最大值抑制nms
    HMM,MEMM,CRF模型
    [bzoj2301][HAOI2011]Problem b
    [洛谷P3935]Calculating
    [bzoj4816][Sdoi2017]数字表格
  • 原文地址:https://www.cnblogs.com/cv-pr/p/6928099.html
Copyright © 2011-2022 走看看