Caffe(二)使用Python運用caffemodel進行mnist數據集預測

Problem Solve

caffe入門與實踐-LeNet MNIST 教程
使用draw_net.py出錯

出錯截圖

出現以上截圖,經百度之后原因為Ubuntu``protobuff的版本較高,導致出錯,然而并沒有找到解決辦法。已找到解決辦法

但隨即又出現'int object has no attribute '__values問題,百度Google易一通之后,依然無解。然后在Caffe GithubIssue模塊中找到這個問題,原來是最新版本draw.py的Bug,下載caffe-rc4.zip替換之后成功解決問題

轉換mnist ubyte3到圖像

參考:使用轉換mnist數據庫保存為bmp圖片

代碼如下

# -*- coding:utf-8 -*-

import struct
import numpy as np
import matplotlib.pyplot as plt
# import Image
from PIL import Image  # import Image seems not work. 
#二進制的形式讀入
filename='train-images-idx3-ubyte'
binfile=open(filename,'rb')
buf=binfile.read()
#大端法讀入4個unsigned int32
#struct用法參見網站 http://www.cnblogs.com/gala/archive/2011/09/22/2184801.html

index=0
magic,numImages,numRows,numColumns=struct.unpack_from('>IIII',buf,index)
index+=struct.calcsize('>IIII')
numImages = 200  # 200 images is enough!
#將每張圖片按照格式存儲到對應位置
for image in range(0,numImages):
    im=struct.unpack_from('>784B',buf,index)
    index+=struct.calcsize('>784B')
   #這里注意 Image對象的dtype是uint8,需要轉換
    im=np.array(im,dtype='uint8')
    im=im.reshape(28,28)
   # fig=plt.figure()
   # plotwindow=fig.add_subplot(111)
   # plt.imshow(im,cmap='gray')
   # plt.show()
    im=Image.fromarray(im)
    im.save('train/train_%s.bmp'%image,'bmp')

使用模型配合OpenCV進行預測

參考:caffe入門與實踐-LeNet MNIST 教程

在參考的基礎上,將模型用于連續預測多張圖像,并配合OpenCV給出識別效果。經過修改后的代碼如下:

# -*- coding:utf-8 -*-
# Modified by NoneLand

# 作者:曉雷
# 鏈接:https://zhuanlan.zhihu.com/p/24110318
# 來源:知乎
# 著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。

import sys
import numpy as np
import cv2

caffe_root = '/home/noneland/Software/caffe-master/'
# This place must use full-path instead of ~. Otherwise netfile can't be open.
sys.path.insert(0, caffe_root + 'python')  # 把pycaffe所在路徑添加到環境變量
import caffe

# 指定網絡結構 與 lenet_train_test.prototxt不同
MODEL_FILE = caffe_root + '/examples/mnist/lenet.prototxt'
PRETRAINED = caffe_root + '/examples/mnist/lenet_iter_10000.caffemodel'
net = caffe.Classifier(MODEL_FILE, PRETRAINED)
caffe.set_mode_cpu()

IMAGE_PATH = '/home/noneland/WorkSpace/mnist_opencv_union/train/'
font = cv2.FONT_HERSHEY_SIMPLEX

for i in range(0, 200):
    # input_image = caffe.io.load_image(IMAG‵E_PATH + 'train_{}.bmp'.format(i), color=False)
    # astype() is a method provided by numpy to convert numpy dtype.
    input_image = cv2.imread(IMAGE_PATH + 'train_{}.bmp'.format(i), cv2.IMREAD_GRAYSCALE).astype(np.float32)
    resized = cv2.resize(input_image, (280, 280), None, 0, 0, cv2.INTER_AREA)
    # resize Image to improve vision effect.
    input_image = input_image[:, :, np.newaxis] # input_image.shape is (28, 28, 1), with dtype float32
    # The previous two lines(exclude resized line) is the same as what caffe.io.load_iamge() do.
    # According to the source code, caffe load_image uses skiamge library to load image from disk.

    # for debug
    # print type(input_image), input_image.shape, input_image.dtype
    # print input_image

    prediction = net.predict([input_image], oversample=False)
    cv2.putText(resized, str(prediction[0].argmax()), (200, 280), font, 4, (255,), 2, cv2.LINE_AA)
    cv2.imshow("Prediction", resized)
    print 'predicted class:', prediction[0].argmax()
    keycode = cv2.waitKey(0) & 0xFF
    if keycode == 27:
        break

識別效果如下:

mnist prediction

整體上來看,在網絡模型的生成階段(即net = caffe.Classifier(MODEL_FILE, PRETRAINED))執行比較緩慢(此句存在較多的輸出語句,后期可以考慮抑制輸出以提高性能),后邊的前向預測可以達到很高的實時性(這還是在CPU模式下,利用妙算的GPU性能或許可以進一步提高性能,降低延遲)。但是LeNet網絡模型較小,不知道AlexNet表現如何。

此外,在查看對應源代碼之后,用OpenCV的接口重寫了加載圖像的方法。從代碼里面可以看出,image對象與numpy關系緊密,單個像素點的操作直接可以用numpy的操作去做,一些需要聯立像素點的操作才需要用OpenCV的函數(暫時這么理解)。不明白作者既然用了OpenCV庫,為何不使用OpenCV的接口來加載圖像,難道是為了提升IO性能,但是不同的庫從磁盤中加載圖像的差異又有多大呢?弄不明白。但是有一點很清楚,caffe的模塊化程度確實很高,在自己寫了加載圖像之后仍然能正常的進行預測,只是在重寫的過程中需要注意數組的尺寸(shape)和元素數據類型(dtype)一致,不然會出現問題。

其他

使用了Linux下面的byzanz工具配合xdotool(用于提取鼠標位置)制作動態圖,效果很好。命令如下:

noneland@NoneLand4DL:~$ xdotool getmouselocation
noneland@NoneLand4DL:~$ sudo byzanz-record -d 30 --delay 5 -c -x 0 -y 0 -w 1280 -h 1080 lenet.gif

`byzanz`使用截圖

另外,開源錄屏軟件OBS也很好用,很多直播就是用的基于OBS的軟件。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容