python使用訓練出的caffemodel模型

環境

模型:訓練出的caffemodel模型
標籤:synset_word.txt
mean:train_mean.npy

使用

上一篇我們訓練出了caffemodel模型,來給c++程序調用。本篇表述使用該模型,python語言。

Caffe均值文件mean.binaryproto轉mean.npy

分享代碼如下:https://blog.csdn.net/hyman_yx/article/details/51732656

import caffe
import numpy as np

MEAN_PROTO_PATH = 'mean.binaryproto'               # 待轉換的pb格式圖像均值文件路徑
MEAN_NPY_PATH = 'mean.npy'                         # 轉換後的numpy格式圖像均值文件路徑

blob = caffe.proto.caffe_pb2.BlobProto()           # 創建protobuf blob
data = open(MEAN_PROTO_PATH, 'rb' ).read()         # 讀入mean.binaryproto文件內容
blob.ParseFromString(data)                         # 解析文件內容到blob

array = np.array(caffe.io.blobproto_to_array(blob))# 將blob中的均值轉換成numpy格式,array的shape (mean_number,channel, hight, width)
mean_npy = array[0]                                # 一個array中可以有多組均值存在,故需要通過下標選擇其中一組均值
np.save(MEAN_NPY_PATH ,mean_npy)

synset_words.txt

這是類別的標籤文件,根據例子更改如下:

0 blue
1 red
2 orange
....

分類

在程序中讀取模型文件處理測試圖片,代碼如下:https://blog.csdn.net/baterforyou/article/details/71430284

    # -*- coding: UTF-8 -*-  
    import os  
    import caffe  
    import numpy as np  
    root='/home/zf/caffe/'#指定根目錄  
    deploy=root+'models/bvlc_reference_caffenet/deploy.prototxt'#結構文件  
    caffe_model=root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'  
    #已經訓練好的model  

    dir =root+'examples/images/'#保存測試圖片的集合  
    filelist=[]  
    filenames=os.listdir(dir)  
    for fn in filenames:  
            fullfilename = os.path.join(dir,fn)  
            filelist.append(fullfilename)  
    #filelist.append(fn)  
    def Test(img):  
    #加載模型  
            net = caffe.Net(deploy,caffe_model,caffe.TEST)  

    # 加載輸入和配置預處理  
            transformer = caffe.io.Transformer({'data':net.blobs['data'].data.shape})  
            transformer.set_mean('data', np.load('/home/zf/caffe/python/caffe/imagenet/ilsvrc_2012_mean.npy').mean(1).mean(1))  
            transformer.set_transpose('data', (2,0,1))  
            transformer.set_channel_swap('data', (2,1,0))  
            transformer.set_raw_scale('data', 255.0)  

    #注意可以調節預處理批次的大小  
    #由於是處理一張圖片,所以把原來的10張的批次改爲1  
            net.blobs['data'].reshape(1,3,227,227)  

    #加載圖片到數據層  
            im = caffe.io.load_image(img)  
            net.blobs['data'].data[...] = transformer.preprocess('data', im)  

    #前向計算  
            out = net.forward()  

    # 其他可能的形式 : out = net.forward_all(data=np.asarray([transformer.preprocess('data', im)]))  

    #預測分類  
            print out['prob'].argmax()

    #打印預測標籤  
            labels = np.loadtxt("/home/zf/caffe/data/ilsvrc12/synset_words.txt", str, delimiter='\t')  
            top_k = net.blobs['prob'].data[0].flatten().argsort()[-1]  
            print 'the class is:',labels[top_k]  
            f=file("/home/zhengfeng/caffe/examples/zf/label.txt","a")  
            f.writelines(img+' '+labels[top_k]+'\n')  
    labels_filename=root +'data/ilsvrc12/synset_words.txt'  
    #循環遍歷文件夾root+'examples/images/'下的所有圖片  
    for i in range(0,len(filelist)):  
            img=filelist[i]  
            Test(img)  

其他

error: * Error parsing text-format caffe.NetParameter: 7:15: Message type “caffe.LayerParameter” has no field named “input_param”

在faster-rcnn體系中使用標準caffe訓練出的模型,其deploy.txt文件格式已經發生了稍微改變,改動如下:

# caffe deploy.txt
name:"GoogleNet"
layer{
name:"data"
type:"Input"
top:"data"
input_param{shape:{dim:1 dim:3 dim:224 dim:224}}
}


# py-faster-rcnn caffe 沒有deploy.txt,這裏使用原模型的deploy.txt(進行如下更改)
input:"data"
input_shape{
dim:1
dim:3
dim:224
dim:224
}
input:"im_info"
input_shape{
dim:1
dim:3
}
發佈了54 篇原創文章 · 獲贊 17 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章