1. 程式人生 > >Caffe學習:4. 使用訓練好的caffemodel(python)

Caffe學習:4. 使用訓練好的caffemodel(python)

在嘗試過 mnist 資料集進行測試後,想要對任意一張圖片進行識別測試,所以將目光瞄準了GoogleNet。在Caffe安裝好後就會有GoogleNet的example,在model種就可以找到。

————————————————————————————————————————————————————————————

因為要使用Python,所以又重新編譯了一遍Caffe,加了Python的相容,重新編譯了pycaffe,需要安裝python2.7,配置好路徑,pipi安裝numpy,boost庫,然後應該就可以編譯通過了,之後python2.7呼叫的時候,會報一些錯,只需要新增相應的包就可以了。

成功好測試一下。

————————————————————————————————————————————————————————————

開啟 readme.md,然後複製裡面的連結,下載已經訓練好的CaffeMdel。

有點慢,文末附加上傳地址吧。

將下載好的caffemodel放入model裡面,或者自己新建的工程目錄中都可以。

接下來新建一個文字,是訓練的模型裡面的所有分類資訊。

大致是這樣子的,一共有1000類。到此,所有的準備材料都OK了。

現在開始準備Python的程式碼。

首先,匯入包:

import caffe
import numpy as np
import matplotlib.pyplot as plt
import os
import PIL
from PIL import Image
import sys
import time

之後,配置一些預設的目錄:

#定義Caffe根目錄
caffe_root = 'F:/caffe/caffe/'
#網路結構描述檔案
deploy_file = caffe_root+'models/bvlc_googlenet/deploy.prototxt'
#訓練好的模型
model_file = caffe_root+'models/bvlc_googlenet/bvlc_googlenet.caffemodel'

設定CPU模式:

#cpu模式
caffe.set_mode_cpu()

新建一個網路結構:

#定義網路模型
net = caffe.Classifier(deploy_file, #呼叫deploy檔案
                       model_file,  #呼叫模型檔案
                       mean=np.load(caffe_root +'python/caffe/imagenet/ilsvrc_2012_mean.npy').mean(1).mean(1), #呼叫均值檔案
                       channel_swap=(2,1,0),  #caffe中圖片是BGR格式,而原始格式是RGB,所以要轉化
                       raw_scale=255,         #python中將圖片儲存為[0, 1],而caffe中將圖片儲存為[0, 255],所以需要一個轉換

其中mean那一條是在caffe編譯好了之後就會有的。

載入寫好的Labels:

#分類標籤檔案
imagenet_labels_filename = caffe_root +'models/bvlc_googlenet/synset_words.txt'
#載入分類標籤檔案
labels = np.loadtxt(imagenet_labels_filename, str, delimiter='\t')

最後開始預測:

#對目標路徑中的影象,遍歷並分類
for root,dirs,files in os.walk(caffe_root+'models/bvlc_googlenet/image/'):
    for file in files:
        #載入要分類的圖片
        image_file = os.path.join(root,file)
        input_image = caffe.io.load_image(image_file)
        # print(type(input_image))
        #列印圖片路徑及名稱
        image_path = os.path.join(root,file)
        print(image_path)
        
        #顯示圖片
        img=Image.open(image_path)
        plt.imshow(img)
        plt.axis('off')
        plt.show()
        
        #預測圖片類別
        time_start = time.time()
        prediction = net.predict([input_image])
        time_end = time.time() - time_start
        print 'Use time',time_end 
        print 'predicted class:',prediction[0].argmax()

        # 輸出概率最大的前5個預測結果
        top_k = prediction[0].argsort()[-5:][::-1]
        for node_id in top_k:     
            #獲取分類名稱
            human_string = labels[node_id]
            #獲取該分類的置信度
            score = prediction[0][node_id]
            print('%s (score = %.5f)' % (human_string, score))

在工程目錄下新建一個image資料夾,在該資料夾下放入想要預測的圖片:

預測結果:

 可以看到用了2.5秒進行預測,但是效果還是比較好的。

程式碼來自覃老師的課堂。