Problem Solve
caffe入門與實踐-LeNet MNIST 教程
使用draw_net.py
出錯
出現(xiàn)以上截圖绘证,經(jīng)百度之后原因為
Ubuntu``protobuff
的版本較高,導致出錯嚷那,然而并沒有找到解決辦法魏宽。已找到解決辦法
但隨即又出現(xiàn)'int object has no attribute '__values
問題,百度Google易一通之后队询,依然無解。然后在Caffe Github
的Issue
模塊中找到這個問題铆惑,原來是最新版本draw.py
的Bug,下載caffe-rc4.zip替換之后成功解決問題丑蛤。
轉換mnist ubyte3到圖像
參考:使用轉換mnist數(shù)據(jù)庫保存為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用法參見網(wǎng)站 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進行預測
在參考的基礎上,將模型用于連續(xù)預測多張圖像棉饶,并配合OpenCV
給出識別效果镇匀。經(jīng)過修改后的代碼如下:
# -*- coding:utf-8 -*-
# Modified by NoneLand
# 作者:曉雷
# 鏈接:https://zhuanlan.zhihu.com/p/24110318
# 來源:知乎
# 著作權歸作者所有。商業(yè)轉載請聯(lián)系作者獲得授權岩梳,非商業(yè)轉載請注明出處晃择。
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所在路徑添加到環(huán)境變量
import caffe
# 指定網(wǎng)絡結構 與 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
識別效果如下:
整體上來看宫屠,在網(wǎng)絡模型的生成階段(即net = caffe.Classifier(MODEL_FILE, PRETRAINED)
)執(zhí)行比較緩慢(此句存在較多的輸出語句滑蚯,后期可以考慮抑制輸出以提高性能),后邊的前向預測可以達到很高的實時性(這還是在CPU模式
下坤次,利用妙算的GPU性能或許可以進一步提高性能斥赋,降低延遲)。但是LeNet
網(wǎng)絡模型較小疤剑,不知道AlexNet
表現(xiàn)如何。
此外疑故,在查看對應源代碼之后弯菊,用OpenCV的接口重寫了加載圖像的方法。從代碼里面可以看出,image
對象與numpy
關系緊密软舌,單個像素點的操作直接可以用numpy
的操作去做育瓜,一些需要聯(lián)立像素點的操作才需要用OpenCV
的函數(shù)(暫時這么理解)。不明白作者既然用了OpenCV庫躏仇,為何不使用OpenCV的接口來加載圖像,難道是為了提升IO性能糟描,但是不同的庫從磁盤中加載圖像的差異又有多大呢书妻?弄不明白。但是有一點很清楚见间,caffe的模塊化程度確實很高工猜,在自己寫了加載圖像之后仍然能正常的進行預測,只是在重寫的過程中需要注意數(shù)組的尺寸(shape
)和元素數(shù)據(jù)類型(dtype
)一致篷帅,不然會出現(xiàn)問題。
其他
使用了Linux下面的byzanz
工具配合xdotool
(用于提取鼠標位置)制作動態(tài)圖惊橱,效果很好箭昵。命令如下:
noneland@NoneLand4DL:~$ xdotool getmouselocation
noneland@NoneLand4DL:~$ sudo byzanz-record -d 30 --delay 5 -c -x 0 -y 0 -w 1280 -h 1080 lenet.gif
另外,開源錄屏軟件OBS
也很好用掉房,很多直播就是用的基于OBS的軟件慰丛。