【caffe】用訓練好的imagenet模型分類圖像

由於畢設須要,我首先是用ffmpeg抽取某個寵物視頻的關鍵幀,而後用caffe對這個關鍵幀中的物體進行分類。python

1.抽取關鍵幀的命令:網絡

E:\graduation design\FFMPEG\bin>ffmpeg -i .\3.mp4 -vf select='eq(pict_type\,I)',setpts='N/(25*TB)' .\%09d.jpg

2.用python編寫腳本,利用在imagenet上訓練的模型分類視頻幀中的物體。函數

抽取獲得的視頻關鍵幀都存放在文件夾"/home/sunshineatnoon/Downloads/dogs/dogs/"中,利用python的walk函數遍歷文件夾中的圖像並分類。spa

代碼以下:3d

 1 import numpy as np
 2 import matplotlib.pyplot as plt
 3 import os
 4 
 5 caffe_root = '/home/sunshineatnoon/Downloads/caffe/'
 6 import sys
 7 sys.path.insert(0,caffe_root+'python')
 8 
 9 import caffe
10 
11 MODEL_FILE = caffe_root+'models/bvlc_reference_caffenet/deploy.prototxt'
12 PRETRAINED = caffe_root+'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'
13 
14 #cpu模式
15 caffe.set_mode_cpu()
16 #定義使用的神經網絡模型
17 net = caffe.Classifier(MODEL_FILE, PRETRAINED,
18                mean=np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy').mean(1).mean(1),
19                channel_swap=(2,1,0),
20                raw_scale=255,
21                image_dims=(256, 256))
22 imagenet_labels_filename = caffe_root + 'data/ilsvrc12/synset_words.txt'
23 labels = np.loadtxt(imagenet_labels_filename, str, delimiter='\t')
24 
25 #對目標路徑中的圖像,遍歷並分類
26 for root,dirs,files in os.walk("/home/sunshineatnoon/Downloads/dogs/dogs/"):
27     for file in files:
28         #加載要分類的圖片
29         IMAGE_FILE = os.path.join(root,file).decode('gbk').encode('utf-8');
30         input_image = caffe.io.load_image(IMAGE_FILE)
31         
32         #預測圖片類別
33         prediction = net.predict([input_image])
34         print 'predicted class:',prediction[0].argmax()
35 
36         # 輸出機率最大的前5個預測結果
37         top_k = net.blobs['prob'].data[0].flatten().argsort()[-1:-6:-1]
38         print labels[top_k]

一張圖像的分類結果以下圖所示:code

分類結果:視頻

這裏不得不感嘆下caffe和神經網絡的強大,儘管視頻幀的分辨率已經這麼低了,仍是在前5個預測中獲得了正確的分類:corgiblog

還有一張特別驚訝的:圖片

分類結果:utf-8

這樣都能檢測出giant panda和cat,太牛了!

相關文章
相關標籤/搜索