Windows7 64bit VS2013 Caffe test MNIST操作步骤
在http://blog.csdn.net/fengbingchun/article/details/49849225中用Caffe对MNIST数据库进行训练,产生了model。下面介绍下如何将产生的model应用在实际的数字图像识别中。
用到的测试图像与http://blog.csdn.net/fengbingchun/article/details/50573841中相同,总共10幅,如下:
在test时与train时的prototxt文件若有不同,test时的prototxt文件修改为如下:
name: "LeNet"
layer {name: "data"type: "MemoryData"top: "data"top: "label"memory_data_param {batch_size: 1channels: 1height: 28width: 28}transform_param {scale: 0.00390625}
}
layer {name: "conv1"type: "Convolution"bottom: "data"top: "conv1"param {lr_mult: 1}param {lr_mult: 2}convolution_param {num_output: 20kernel_size: 5stride: 1weight_filler {type: "xavier"}bias_filler {type: "constant"}}
}
layer {name: "pool1"type: "Pooling"bottom: "conv1"top: "pool1"pooling_param {pool: MAXkernel_size: 2stride: 2}
}
layer {name: "conv2"type: "Convolution"bottom: "pool1"top: "conv2"param {lr_mult: 1}param {lr_mult: 2}convolution_param {num_output: 50kernel_size: 5stride: 1weight_filler {type: "xavier"}bias_filler {type: "constant"}}
}
layer {name: "pool2"type: "Pooling"bottom: "conv2"top: "pool2"pooling_param {pool: MAXkernel_size: 2stride: 2}
}
layer {name: "ip1"type: "InnerProduct"bottom: "pool2"top: "ip1"param {lr_mult: 1}param {lr_mult: 2}inner_product_param {num_output: 500weight_filler {type: "xavier"}bias_filler {type: "constant"}}
}
layer {name: "relu1"type: "ReLU"bottom: "ip1"top: "ip1"
}
layer {name: "ip2"type: "InnerProduct"bottom: "ip1"top: "ip2"param {lr_mult: 1}param {lr_mult: 2}inner_product_param {num_output: 10weight_filler {type: "xavier"}bias_filler {type: "constant"}}
}
layer {name: "prob"type: "Softmax"bottom: "ip2"top: "prob"
}
测试代码如下:#include <iostream>
#include <glog/logging.h>
#include <cstring>
#include <map>
#include <string>
#include <vector>#include "boost/algorithm/string.hpp"
#include "caffe/caffe.hpp"
#include "caffe/util/io.hpp"
#include "caffe/blob.hpp"#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>using caffe::Blob;
using caffe::Caffe;
using caffe::Net;
using caffe::Layer;
using caffe::shared_ptr;
using caffe::string;
using caffe::Timer;
using caffe::vector;
using std::ostringstream;DEFINE_string(model, "E:/GitCode/Caffe_Test/test_data/model/mnist/lenet_train_test_.prototxt","The model definition protocol buffer text file..");
DEFINE_string(weights, "E:/GitCode/Caffe_Test/test_data/model/mnist/lenet_iter_10000.caffemodel","Optional; the pretrained weights to initialize finetuning, ""separated by ','. Cannot be set simultaneously with snapshot.");// A simple registry for caffe commands.
typedef int(*BrewFunction)();
typedef std::map<caffe::string, BrewFunction> BrewMap;
BrewMap g_brew_map;#define RegisterBrewFunction(func) \
namespace { \
class __Registerer_##func { \public: /* NOLINT */ \__Registerer_##func() { \g_brew_map[#func] = &func; \} \
}; \
__Registerer_##func g_registerer_##func; \
}static BrewFunction GetBrewFunction(const caffe::string& name) {if (g_brew_map.count(name)) {return g_brew_map[name];}else {LOG(ERROR) << "Available caffe actions:";for (BrewMap::iterator it = g_brew_map.begin();it != g_brew_map.end(); ++it) {LOG(ERROR) << "\t" << it->first;}LOG(FATAL) << "Unknown action: " << name;return NULL; // not reachable, just to suppress old compiler warnings.}
}// caffe commands to call by
// caffe <command> <args>
//
// To add a command, define a function "int command()" and register it with
// RegisterBrewFunction(action);// Test: score a model.
int test() {CHECK_GT(FLAGS_model.size(), 0) << "Need a model definition to score.";CHECK_GT(FLAGS_weights.size(), 0) << "Need model weights to score.";LOG(INFO) << "Use CPU.";Caffe::set_mode(Caffe::CPU);// Instantiate the caffe net.Net<float> caffe_net(FLAGS_model, caffe::TEST);caffe_net.CopyTrainedLayersFrom(FLAGS_weights);int target[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};int result[10] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 };std::string image_path = "E:/GitCode/Caffe_Test/test_data/images/";for (int i = 0; i < 10; i++) {char ch[15];sprintf(ch, "%d", i);std::string str;str = std::string(ch);str += ".png";str = image_path + str;cv::Mat mat = cv::imread(str.c_str(), 1);if (!mat.data) {std::cout << "load image error" << std::endl;return -1;}cv::cvtColor(mat, mat, CV_BGR2GRAY);cv::resize(mat, mat, cv::Size(28, 28));cv::bitwise_not(mat, mat);// set the patch for testingvector<cv::Mat> patches;patches.push_back(mat);// push vector<Mat> to data layerfloat loss = 0.0;boost::shared_ptr<caffe::MemoryDataLayer<float> > memory_data_layer;memory_data_layer = boost::static_pointer_cast<caffe::MemoryDataLayer<float>>(caffe_net.layer_by_name("data"));vector<int> labels(patches.size());memory_data_layer->AddMatVector(patches, labels);// Net forwardconst vector<Blob<float>*> & results = caffe_net.ForwardPrefilled(&loss);float *output = results[1]->mutable_cpu_data();float tmp = -1;int pos = -1;// Display the outputstd::cout << "actuarl digit is: " << i << std::endl;for (int j = 0; j < 10; j++) {printf("Probability to be Number %d is %.3f\n", j, output[j]);if (tmp < output[j]) {pos = j;tmp = output[j];}}result[i] = pos;}for (int i = 0; i < 10; i++) {std::cout << "actual digit is : " << target[i] << ", result digit is: " << result[i] << std::endl;}return 0;
}
RegisterBrewFunction(test);int main(int argc, char* argv[])
{// https://initialneil.wordpress.com/2015/07/16/caffe-vs2013-opencv-in-windows-tutorial-ii/// https://initialneil.wordpress.com/2015/01/11/build-caffe-in-windows-with-visual-studio-2013-cuda-6-5-opencv-2-4-9/// https://github.com/BVLC/caffe/issues/2499// http://ju.outofmemory.cn/entry/139417// http://pz124578126.lofter.com/tag/caffe// https://github.com/BVLC/caffe/pull/1907argc = 2;
#ifdef _DEBUG argv[0] = "E:/GitCode/Caffe_Test/lib/dbg/x86_vc12/test_mnist[dbg_x86_vc12].exe";
#else argv[0] = "E:/GitCode/Caffe_Test/lib/rel/x86_vc12/test_mnist[rel_x86_vc12].exe";
#endif argv[1] = "test";// 每个进程中至少要执行1次InitGoogleLogging(),否则不产生日志文件google::InitGoogleLogging(argv[0]);// 设置日志文件保存目录,此目录必须是已经存在的FLAGS_log_dir = "E:\\GitCode\\Caffe_Test\\test_data";FLAGS_max_log_size = 1024;//MB// Print output to stderr (while still logging).FLAGS_alsologtostderr = 1;// Usage message.gflags::SetUsageMessage("command line brew\n""usage: caffe <command> <args>\n\n""commands:\n"" test score a model");// Run tool or show usage.//caffe::GlobalInit(&argc, &argv);// 解析命令行参数 gflags::ParseCommandLineFlags(&argc, &argv, true);if (argc == 2) {return GetBrewFunction(caffe::string(argv[1]))();}else {gflags::ShowUsageWithFlagsRestrict(argv[0], "tools/caffe");}std::cout << "OK!!!" << std::endl;return 0;
}
结果图如下:通过结果发现,准确率为70%,错误的将6、8、9分别误识别为8、2、1。
GitHub:https://github.com/fengbingchun/Caffe_Test
相关文章:
记住这35个英文单词,你就可以在RPA界混了!
无论是想玩转RPA(机器人流程自动化),还是有意了解、进入这项行业,只有先了解该领域的专有名词(行业术语),才能为之后的活动提供更多的可能。UiBot现为您编译整理了这份机器人流程自动化术语表&a…

福利 | 送你一张通往「2019 AI开发者大会」的门票
2019 AI开发者大会(AI ProCon 2019)是由中国IT社区CSDN主办的AI技术与产业年度盛会。多年经验淬炼,如今蓄势待发:2019年9月6-7日,大会将有近百位中美顶尖AI专家、知名企业代表以及千余名AI开发者齐聚北京,进行技术解读和产业论证。…

收缩日志文件夹
-- MSSQL2005 USE mastergo DECLARE dbname sysname;SET dbnameBSV100;-- 清空日志EXEC (DUMP TRANSACTION [dbname] WITH NO_LOG); -- 截断事务日志:EXEC (BACKUP LOG [dbname] WITH NO_LOG); -- 收缩数据库文件(如果不压缩,数据库的文件不会减小EXEC (DBCC SHR…

腾讯AI开源框架Angel 3.0重磅发布:超50万行代码,支持3种算法,打造全栈机器学习平台...
出品 | AI科技大本营(ID:rgznai100)【导语】2019年8月22日,腾讯首个AI开源项目Angel正式发布3.0版本。Angel 3.0尝试打造一个全栈的机器学习平台,功能特性涵盖了机器学习的各个阶段:特征工程,模…

路印协议受邀参加澳洲新南威尔士政府孵化器Haymarket HQ分享论坛
2019年2月15日,澳洲新南威尔士政府孵化器Haymarket HQ和Next Genius 社区联合举办了区块链解决方案分享论坛,路印协议CMO周杰受邀介绍当前交易所现状和路印协议的去中心化解决方案。参与此次论坛的还有区块链开发人员、企业家和去中心化技术爱好者&#…

一步一步指引你在Windows7上配置编译使用Caffe(https://github.com/fengbingchun/Caffe_Test)
之前写过几篇关于Caffe源码在Windows764位上配置编译及使用过程,只是没有把整个工程放到网上,最近把整个工程整理清理了下,把它放到了GitHub上。下面对这个工程的使用作几点说明:1. 整个工程Caffe在Windows7 64位VS2013下编译…

演示:思科IPS在线模式下Inline Interface Mode的响应行为(区别各个防御行为)
演示:思科IPS在线模式下Inline Interface Mode的响应行为演示目标:科IPS在线模式下InlineInterface Mode的响应行为。演示环境:仍然使用图5.16所示的网络环境。演示背景:在VLAN3的主机192.168.4.2上发起对主机192.168.4.1的漏洞扫…
【笔记】重学前端-winter
本文为:winter 发布在极客时间 【重学前端】系列课程的的笔记和总结支持正版哦: https://time.geekbang.org/col... 导语 如果深入进去了解,你会发现,表面上看他们可能是一时忘记了,或者之前没注意但实际上是他们对于前端的知识体…

如何用知识图谱挖掘商业数据背后的宝藏?
这是一个商业时代,一个数据为王的时代,也是一个 AI 迎来黄金发展期的时代。据史料记载,商业在商朝已初具规模。斗转星移,时光流转,到 2019 年,商业形式已发生翻天覆地的变化,但是商业的本质——…
通过define _CRTDBG_MAP_ALLOC宏来检测windows上的code是否有内存泄露
VS中自带了内存泄露检测工具,若要启用内存泄露检测,则在程序中包括以下语句: #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> 它们的先后顺序不能改变。通过包括 crtdbg.h,将malloc和free函数映射到其”Debug”版本_malloc…

java.sql.SQLException: Data truncation: Truncated incorrect DOUBLE value
mysql 报这个异常:java.sql.SQLException: Data truncation: Truncated incorrect DOUBLE value update 表名 set col1 ? and col2 ? where id ? 改为: update 表名 set col1 ? , col2 ? where id ? 用逗号隔开
在Ubuntu14.04 64位上编译CMake源码操作步骤
在Ubuntu上通过apt-get install安装CMake并不是最新版的,这里记录下在Ubuntu上通过源码安装CMake的操作步骤:1. 卸载旧版CMake,执行以下命令:apt-get autoremove cmake如果卸载不掉,则通过执行以下命令删除&…

一份贪心算法区间调度问题解法攻略,拿走不谢
作者 | labuladong来源 | labuladong(ID:labuladong)【导读】什么是贪心算法呢?贪心算法可以认为是动态规划算法的一个特例,相比动态规划,使用贪心算法需要满足更多的条件(贪心选择性质)&#x…

css:z-index
针对position: absolute;解决position:relative;z-index固定定位层级显示问题转载于:https://blog.51cto.com/13507333/2352775

折半查找函数(from 《The C Programming Language》)
该函数用于判定已排序的数组array中是否存在某个特定的值value。这里假定数组元素以升序排列,如果数组array中包含value,则函数返回value在array中的位置(介于0~n-1之间的一个整数);否则,该函数返回-1。 在…
C++中的explicit关键字介绍
C中的关键字explicit主要是用来修饰类的构造函数,被修饰的构造函数的类,不能发生相应的隐式类型转换,只能以显示的方式进行类型转换。类构造函数默认情况下声明为隐式的即implicit。隐式转换即是可以由单个实参来调用的构造函数定义了一个从形…

Redis的集群模式
集群 即使使用哨兵,此时的Redis集群的每个数据库依然存有集群中的所有数据,从而导致集群的总数据存储量受限于可用存储内存最小的数据库节点,形成木桶效应。由于Redis中的所有数据都是基于内存存储,这一问题就尤为突出了尤其是当使…

刚上线就报名2000人!8位大牛免费讲座,再不报名就满额了!
今年是CSDN的第20年,我们已经不再满足解决你的技术问题,还要帮你解决人生大事!为了让你飞黄腾达,我们特别邀请到了8位大牛老师进行直播,他们已经实现了成为技术总监、创业、财富自由的梦想,这场直播&#x…

排序算法之插入排序
插入排序一般分为直接插入排序和二分插入排序。一、直接插入排序:直接插入排序又可以分为前插和后插,不过虽然是这样分,只是寻找地点的方向不一样而已。“前插”就是从头开始找合适的位置,“后插”就是从后面开始找合适的位置。直…

C++中#error/assert/static_assert的区别及使用
C 语言支持可帮助您调试应用程序的三个错误处理机制:#error 指令、static_assert 关键字和 assert (CRT) 宏。所有的三种机制都会发出错误消息。#error可看做预编译期断言,甚至都算不上断言,仅仅能在预编译时显示一个错误信息,它能…

读完ACL 2019录取的30篇知识图谱论文,我发现了这5点趋势
作者 | Michael Galkin译者 | Freesia编辑 | 夕颜出品 | AI科技大本营(ID: rgznai100)【导读】近年来,自然语言处理领域中广泛应用的知识图谱(KGs)正在不断地吸引人们的目光,此次 ACL 2019 中的有关于知识图…

力扣(LeetCode)933
题目地址:https://leetcode-cn.com/probl...题目描述:写一个 RecentCounter 类来计算最近的请求。 它只有一个方法:ping(int t),其中 t 代表以毫秒为单位的某个时间。 返回从 3000 毫秒前到现在的 ping 数。 任何处于 [t - 3000, …

2013年10月1日C#随机数
最近开始接触C跟C#,总是有人说女生本来就不适合做程序,就连今天都听到有人这样跟我讲,不过呢没有关系,我相信男生不一定比女生厉害多少,就好像我身边就有一位男生就总是觉得我的程序比他好一点就是理所当然的ÿ…

C/C++中inline/static inline/extern inline的区别及使用
引入内联函数的目的是为了解决程序中函数调用的效率问题,也是用内联函数取代带参宏定义(函数传参比宏更加方便易用)inline关键字用来定义一个类的内联函数。在类体中和类体外定义成员函数是有区别的:在类体中定义的成员函数为内联…

RISC-V架构上的Debian和Fedora现状
RISC-V仍然是开源/Linux用户非常感兴趣的,因为它是免版税且完全开放的CPU架构。部分原因是由于缺乏经济实惠的RISC-V硬件,限制了开发人员在这种架构上的更多工作,Linux发行版支持的RISC-V状态各不相同,但近年来至少有所改善。在上…

字节跳动李航:自学机器学习,研究AI三十载,他说AI发展或进入平缓期
作者 | 夕颜出品 | AI科技大本营(ID:rgznai100)【导读】一阵凉风吹过人工智能,让这个曾是燥热的领域逐渐冷却下来,留下的是扎实地在做研究的人、机构、企业。先后在 NEC 公司中央研究所、微软亚洲研究院、华为诺亚方舟实验室从事和…

PC上安装MAC X Lion
PC上安装MACXLion网上关于如何在PC下安装MAC的文章已近不少了,但对于一些初学者在实践当中会遇到各种问题,以下视频资料为大家展示两种虚拟机安装MacOS。1.VmwareWorkstation在虚拟机中安装首先将插件装好(在远景上下载)ÿ…

C++中static_cast/const_cast/dynamic_cast/reinterpret_cast的区别和使用
C风格的强制转换较简单,如将float a转换为int b,则可以这样:b (int)a,或者bint(a)。 C类型转换分为隐式类型转换和显示类型转换。 隐式类型转换又称为标准转换,包括以下几种情况: (1)、算术转换&#x…

行为型模式:命令模式
LieBrother原文: 行为型模式:命令模式 十一大行为型模式之三:命令模式。 简介 姓名 :命令模式 英文名 :Command Pattern 价值观 :军令如山 个人介绍 : Encapsulate a request as an object,ther…

与旷视、商汤等上百家企业同台竞技?AI Top 30+案例评选等你来秀!
人工智能历经百年发展,如今迎来发展的黄金时期。目前,AI 技术已涵盖自然语言处理、模式识别、图像识别、数据挖掘、机器学习等领域的研究,在汽车、金融、教育、医疗、安防、零售、家居、文娱、工业等行业获得了令人印象深刻的成果。在各行业宣…