首先下载caffemodel、要预测的图片、prototxt等文件,地址如下:下载(需要优快云帐号,需要2积分,优快云取消了0积分下载,我也没办法)
百度网盘 密码: 56sy
然后解压、并进入解压后的目录
windows平台:
官方发布了编译好的可执行文件,太贴心了, 下载地址如下:caffe 向下拉,找到 Prebuilt binaries 那里就是。
解压编译好的caffe之后, 记得把caffe/bin的路径放进环境变量里去
classification lenet.prototxt lenet_iter_10000.caffemodel mean.binaryproto labels.txt 7.jpg
Linux平台:
通过 caffe进行预测
~/caffe/build/tools/caffe test -model=lenet_train_test.prototxt -weights=lenet_iter_10000.caffemodel
通过python进行预测
import caffe
import numpy as np
import cv2
model = 'py_lenet.prototxt'
weights = 'lenet_iter_10000.caffemodel'
img_file = "7.jpg"
def transform_img(img, img_width, img_height):
img = cv2.resize(img, (img_width, img_height), interpolation = cv2.INTER_CUBIC)
return img
net = caffe.Net(model, weights, caffe.TEST)
img = cv2.imread(img_file, cv2.IMREAD_GRAYSCALE)
#img = transform_img(img, 28, 28)
net.blobs['data'].data[...] = img
out = net.forward()
prob = out['prob'][0]
print prob
for index, item in enumerate(prob):
if item == 1:
print index
下面说下我碰到的问题
怎么安装caffe和训练mnist我就不说了, 参见其它文章
刚开始无论是使用python还是使用caffe可执行程序, 一直预测不准,而且每次结果都不一样。郁闷了几个小时,从网上下载别人训练好的模型也是一样, 结果不对。 我怀疑可能是 prototxt或者是图片不对。然后各种修改prototxt,依旧各种不对。 最后没办法了, 只能从图片上找原因了, 由于训练使用的LMDB数据库,我就把我的图片转成LMDB格式。 还是不对, 彻底凌乱了。最后从网上找了份代码, 读取LMDB数据库, 然后保存1张图片, 然后我打开看了下, 差点吐血, 网上下载的图片是黑字白底, 我训练的是黑底白字。 后面就在windows平台预测顺利通过,python也很快就预测通过。
读取LMDB并保存图片的代码如下:
import numpy as np
import lmdb
import caffe
import cv2
from matplotlib import pyplot
from caffe.proto import caffe_pb2
lmdbpath = "./mnist_test_lmdb"
lmdb_env = lmdb.open(lmdbpath, readonly=True)
lmdb_txn = lmdb_env.begin()
lmdb_cursor = lmdb_txn.cursor()
datum = caffe_pb2.Datum()
for key, value in lmdb_cursor:
datum.ParseFromString(value)
data = caffe.io.datum_to_array(datum)
image = data.transpose(1, 2, 0)
cv2.imwrite ("tt.jpg", image);
break
在Linux平台使用caffe可执行文件预测又有问题, 一直报如下错误:
Cannot copy param 0 weights from layer 'conv1'; shape mismatch. Source param shape is 20 1 5 5 (500); target param shape is 20 3 5 5 (1500). To learn this layer's parameters from scratch rather than copying from a saved net, rename the layer.
图片是单通道的, 训练也是单通道的, 为啥会有这个问题呢, 同样郁闷了几个小时, 怀疑是prototxt文件没有写对, 然后到网上查image_data_param怎么哪个选项是读取单通道的, 无果, 只有看caffe的代码了
发现在image_data_layer.cpp中, 有个ReadImageToCVMat, 然后在src/caffe/util/io.cpp中有实现, 其中有个参数是is_color, 最后在image_data_param里面加上
is_color : 0
至此, MNIST算是跑通了
最后希望这篇文章对你有帮助, 少走些弯路。
注:以上代码均经过测试