转载:http://blog.csdn.net/u013407923/article/details/53084984
在之前的实验中我们使用过
$ ./build/tools/caffe.bin test \
-model examples/mnist/lenet_train_test.prototxt \
-weights examples/mnist/lenet_iter_10000.caffemodel \
-iterations 100
命令来测试训练好的网络。这主要用于测试网络的准确率。
但如想用自己的手写数字,通过训练好的模型来识别这个数字,怎么做呢?
可以使用Caffe中build/examples/cpp_classification/classification.bin这个程序来实现。
$ ./build/examples/cpp_classification/classification.bin
Usage: ./build/examples/cpp_classification/classification.bin
deploy.prototxt // 模型描述文件
network.caffemodel // 模型权值文件
mean.binaryproto // 图像均值文件
labels.txt // 图像类别标签信息
img.jpg // 输入待分类图像
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7
接下来开始准备这几个文件
模型描述文件
将lenet_train_test.prototxt复制一份修改如下
// 将训练和测试用的mnist层删除,添加以下层
name: "LeNet"
layer {
name: "data"
type: "Input"
top: "data"
input_param { shape: { dim: 1 dim: 1 dim: 28 dim: 28 } }
}
......
// 中间的模型不改动,省略
......
// 将accuracy层和loss层删除,添加以下层
layer {
name: "prob"
type: "Softmax"
bottom: "ip2"
top: "prob"
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
权值描述文件
训练好网络后examples/mnist/目录下就会会有lenet_iter_10000.caffemodel这个文件。
图像均值文件
Caffe框架为我们提供了一个计算均值的文件compute_image_mean.cpp,放在caffe根目录下的tools文件夹里面。编译后的可执行体放在 build/tools/ 下面,我们直接调用就可以了
$ sudo build/tools/compute_image_mean examples/mnist/mnist_train_lmdb examples/mnist/mean.binaryproto
- 1
- 1
带两个参数:
第一个参数:examples/mnist/mnist_train_lmdb, 表示需要计算均值的数据,格式为lmdb的训练数据。
第二个参数:examples/mnist/mean.binaryproto, 计算出来的结果保存文件。
标签文件
新建label.txt,每行一个数字,0到9。
0
1
2
3
4
5
6
7
8
9
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
输入待分类图像
这个自己拿画图工具画一个就好。由于训练集中的数据都是黑底白字的,所以如果自己写是是白底黑字的图片可能识别不准确。
开始测试
$ ./build/examples/cpp_classification/classification.bin \
examples/mnist/classificat_net.prototxt \
examples/mnist/lenet_iter_10000.caffemodel \
examples/mnist/mean.binaryproto examples/mnist/label.txt \
examples/mnist/0.png
---------- Prediction for examples/mnist/0.png ----------
1.0000 - "0"
0.0000 - "1"
0.0000 - "3"
0.0000 - "4"
0.0000 - "2"
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
结果显示图片中的数字为0。