1. 程式人生 > >從零開始學caffe(七):利用GoogleNet實現影象識別

從零開始學caffe(七):利用GoogleNet實現影象識別

一、準備模型

在這裡,我們利用已經訓練好的Googlenet進行物體影象的識別,進入Googlenet的GitHub地址,進入models資料夾,選擇Googlenet 在這裡插入圖片描述 點選Googlenet的模型下載地址下載該模型到電腦中。

模型結構

在這裡,我們利用之前講到的網路模型繪製網站畫出Googlenet的結構圖如下: 在這裡插入圖片描述

  • 在這裡,pad就是給影象補零,pad:2就是補兩圈零的意思;

  • LRN就是區域性相應歸一化,利用LRN可以提高模型識別的準確率;

  • Inception結構中,不同大小的卷積核意味著不同大小的感受野,最後的合併意味著不同尺度特徵的融合。採用1,3,5為卷積核的大小,是因為使用步長為1,pad=0,1,2的方式取樣之後得到的特徵平面大小相同;

  • concat層用來合併資料,在這裡合併的條件是資料的後三個引數要相同,所以在前面的inception結構中,我們使用了不同的卷積核大小和pad。

準備圖片

在這裡,我們找幾張任意圖片,然後放入Googlenet的資料夾下,,作為待識別的圖片。 在這裡插入圖片描述

準備synset_words.txt檔案

synset_words.txt是用來將物體的類別序號進行對應的檔案,在識別過程中,我們先是得到序號,然後根據這個序號找到對應的物體種類。

使用python介面呼叫GoogleNet實現影象識別

在這裡,我們用jupyter開啟Googlenet.影象識別.ipynb檔案,這裡部分程式碼如下:

import
caffe import numpy as np import matplotlib.pyplot as plt import os import PIL from PIL import Image import sys #定義Caffe根目錄 caffe_root = 'E:/caffe-windows/' #網路結構描述檔案 deploy_file = caffe_root+'models/bvlc_googlenet/deploy.prototxt' #訓練好的模型 model_file = caffe_root+'models/bvlc_googlenet/bvlc_googlenet.caffemodel'
#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],所以需要一個轉換 image_dims=(224, 224)) #輸入模型的圖片要是224*224的圖片 #分類標籤檔案 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) #列印圖片路徑及名稱 image_path = os.path.join(root,file) print(image_path) #顯示圖片 img=Image.open(image_path) plt.imshow(img) plt.axis('off') plt.show() #預測圖片類別 prediction = net.predict([input_image]) 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))

執行上述程式碼即可輸出對物體種類的預測概率 在這裡插入圖片描述 最終得到的預測結果是根據可能性大小列出五個種類