mnist手写测试
本文主要参考《caffe-之经典模型详解与实战》
目标:用手写的数字输入到网络进行分类识别。
要求:
(1)图片必须是256位黑白色
(2)黑底白字
(3)像素大小为28*28
(4)数字要在图片的中间
以下是代码部分
#import os
import sys
#import numpy as np
#import matplotlib.pyplot as plt
import caffe
caffe_root = '/home/chrisd/caffe/'
sys.path.insert(0,caffe_root+'python')
MODEL_FILE ='/home/chrisd/caffe/examples/mnist/lenet.prototxt'
PRETRAINED ='/home/chrisd/caffe/examples/mnist/lenet_iter_10000.caffemodel'
IMAGE_FILE ='/home/chrisd/caffe/examples/mnist/images/train_33.bmp'
input_image=caffe.io.load_image(IMAGE_FILE,color=False)
#print input_image
net =caffe.Classifier(MODEL_FILE,PRETRAINED)
prediction=net.predict([input_image],oversample=False)
caffe.set_mode_cpu()
print 'predicted class:', prediction[0].argmax()
待测试图片:
实验结果:
mnist样本库的图片转换
代码如下:
import struct
import numpy as np
#import matplotlib.pyplot as plt
import PIL.Image
filename='/home/chrisd/caffe/data/mnist/train-images-idx3-ubyte'
binfile=open(filename,'rb')
buf=binfile.read()
index=0
magic,numImages,numRows,numColumns=struct.unpack_from('>IIII',buf,index)
index+=struct.calcsize('>IIII')
for image in range(0,numImages):
im=struct.unpack_from('>784B',buf,index)
index+=struct.calcsize('>784B')
im=np.array(im,dtype='uint8')
im=im.reshape(28,28)
im=PIL.Image.fromarray(im)
im.save('mnist_train/train_%s.bmp'%image,'bmp')
转换结果: