Caffe任务池GPU模型图像识别
一开始我在网上找demo没有找到,在群里寻求帮助也没有得到结果,索性将网上的易语言模块反编译之后,提取出对应的dll以及代码,然后对照官方的c++代码,写出了下面的c#版本

/***
* @pName caffe_task_pool_demo
* @name CC
* @user wadezh
* @date 2018/6/16
* @desc
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks; namespace caffe_task_pool_demo
{
class CC
{ public static int taskPool { get; set; } = ;
public static string prototxt { get; set; }
public static ArrayList map { get; set; }
public static int timeStep { get; set; }
public static int alphabetSize { get; set; } /*Caffe_API TaskPool* __stdcall createTaskPoolByData( const void* prototxt_data, int prototxt_data_length, const void* caffemodel_data, int caffemodel_data_length, float scale_raw = 1, const char* mean_file = 0, int num_means = 0, float* means = 0, int gpu_id = -1, int batch_size = 3);*/ [DllImport("classification_dll.dll", EntryPoint = "createTaskPoolByData", CallingConvention = CallingConvention.StdCall)]
public static extern int CreateTaskPoolByData(byte[] prototxt_data,
int prototxt_data_length,
byte[] caffemodel_data,
int caffemodel_data_length,
float scale_raw = ,
string mean_file = "",
int num_means = ,
float means = ,
int gpu_id = -,
int cach_size = ); /*Caffe_API BlobData* __stdcall forwardByTaskPool(TaskPool* pool, const void* img, int len, const char* blob_name);*/ [DllImport("classification_dll.dll", EntryPoint = "forwardByTaskPool", CallingConvention = CallingConvention.StdCall)]
public static extern int ForwardByTaskPool(int poolHandle, byte[] image, int imageLen, string printBlobName); /*Caffe_API int __stdcall getBlobLength(BlobData* feature);*/
[DllImport("classification_dll.dll", EntryPoint = "getBlobLength", CallingConvention = CallingConvention.StdCall)]
public static extern int GetBlobLength(int feature); /*Caffe_API void __stdcall cpyBlobData(void* buffer, BlobData* feature);*/
[DllImport("classification_dll.dll", EntryPoint = "cpyBlobData", CallingConvention = CallingConvention.StdCall)]
public static extern int CpyBlobData(float[] buffer, int feature); /*Caffe_API void __stdcall releaseBlobData(BlobData* ptr);*/
[DllImport("classification_dll.dll", EntryPoint = "releaseBlobData", CallingConvention = CallingConvention.StdCall)]
public static extern int ReleaseBlobData(int ptr); private static int Argmax(float[] arr, int begin, int end, ref float acc)
{
acc = -;
int mxInd = ;
for (int i = begin; i < end; i++)
{
if (acc < arr[i])
{
mxInd = i;
acc = arr[i];
}
}
return mxInd - begin;
} public static bool InitCaptcha(string prototxtPath, string modelPath, string mapPath, int gpuId, int batchSize) {
byte[] deploy = Util.GetFileStream(prototxtPath);
byte[] model = Util.GetFileStream(modelPath);
CC.taskPool = CC.CreateTaskPoolByData(deploy, deploy.Length, model, model.Length, 1F, "", , 0F, gpuId, batchSize);
CC.prototxt = System.Text.Encoding.Default.GetString(deploy);
string[] mapFile = Util.LoadStringFromFile(mapPath).Trim().Split("\r\n".ToArray());
CC.map = new ArrayList();
for (int i = ; i < mapFile.Length; i++)
{
if (mapFile[i].Length > )
{
CC.map.Add(mapFile[i]);
}
}
string time_step = Util.GetMiddleString(CC.prototxt, "time_step:", "\r\n");
string layer = Util.GetMiddleString(CC.prototxt, "inner_product_param {", "{");
string alphabet_size = Util.GetMiddleString(layer, "num_output:", "\r\n");
CC.timeStep = int.Parse(time_step);
CC.alphabetSize = int.Parse(alphabet_size);
return CC.taskPool != ;
} public static string GetCaptcha(byte[] image) {
// Get the prediction result handle
int poolHandle = CC.ForwardByTaskPool(taskPool, image, image.Length, "premuted_fc"); // Get the tensor handle
float[] permute_fc = new float[CC.GetBlobLength(poolHandle)]; // Copy the tensor data
CpyBlobData(permute_fc, poolHandle);
string code = string.Empty; if (permute_fc.Length > )
{
int o = ;
float acc = 0F;
int emptyLabel = alphabetSize - ;
int prev = emptyLabel;
for (int i = ; i < timeStep; i++)
{
o = Argmax(permute_fc, (i - ) * alphabetSize + , i * alphabetSize, ref acc);
if (o != emptyLabel && prev != o) code += map[o + ];
prev = o;
}
code = code.Replace("_", "").Trim();
} ReleaseBlobData(poolHandle);
return code;
} protected class Util
{ public static byte[] GetFileStream(string path)
{
FileStream fs = new FileStream(path, FileMode.Open);
long size = fs.Length;
byte[] array = new byte[size];
fs.Read(array, , array.Length);
fs.Close();
return array;
} public static string LoadStringFromFile(string fileName)
{
string content = string.Empty; StreamReader sr = null;
try
{
sr = new StreamReader(fileName, System.Text.Encoding.UTF8);
content = sr.ReadToEnd();
}
catch (Exception ex)
{
throw ex;
} if (sr != null)
sr.Close(); return content;
} public static string GetMiddleString(string SumString, string LeftString, string RightString)
{
if (string.IsNullOrEmpty(SumString)) return "";
if (string.IsNullOrEmpty(LeftString)) return "";
if (string.IsNullOrEmpty(RightString)) return ""; int LeftIndex = SumString.IndexOf(LeftString);
if (LeftIndex == -) return "";
LeftIndex = LeftIndex + LeftString.Length;
int RightIndex = SumString.IndexOf(RightString, LeftIndex);
if (RightIndex == -) return "";
return SumString.Substring(LeftIndex, RightIndex - LeftIndex);
} } } }
项目中我已经将caffemodel以及prototxt等文件都打包,可以直接运行
我封装的这个CC类只支持GPU任务池识别,识别速度比较快
链接:https://pan.baidu.com/s/17tSh3IE3Xv_YlJhSOhKddg 密码:ct5z
Caffe任务池GPU模型图像识别的更多相关文章
- Caffe学习笔记(一):Caffe架构及其模型解析
Caffe学习笔记(一):Caffe架构及其模型解析 写在前面:关于caffe平台如何快速搭建以及如何在caffe上进行训练与预测,请参见前面的文章<caffe平台快速搭建:caffe+wind ...
- Caffe框架GPU与MLU计算结果不一致请问如何调试?
Caffe框架GPU与MLU计算结果不一致请问如何调试? 某一检测模型移植到Cambricon Caffe上时,发现无法检测出结果,于是将GPU和MLU的运行结果输出并保存后进行对比,发现二者计算结果 ...
- Error when Building GPU docker image for caffe: Unsupported gpu architecture 'compute_60'
issue: Error when Building GPU docker image for caffe: Unsupported gpu architecture 'compute_60' rea ...
- 在Caffe中实现模型融合
模型融合 有的时候我们手头可能有了若干个已经训练好的模型,这些模型可能是同样的结构,也可能是不同的结构,训练模型的数据可能是同一批,也可能不同.无论是出于要通过ensemble提升性能的目的,还是要设 ...
- pycaffe︱caffe中fine-tuning模型三重天(函数详解、框架简述)
本文主要参考caffe官方文档[<Fine-tuning a Pretrained Network for Style Recognition>](http://nbviewer.jupy ...
- 基于Caffe训练AlexNet模型
数据集 1.准备数据集 1)下载训练和验证图片 ImageNet官网地址:http://www.image-net.org/signup.php?next=download-images (需用邮箱注 ...
- Caffe学习笔记2--Ubuntu 14.04 64bit 安装Caffe(GPU版本)
0.检查配置 1. VMWare上运行的Ubuntu,并不能支持真实的GPU(除了特定版本的VMWare和特定的GPU,要求条件严格,所以我在VMWare上搭建好了Caffe环境后,又重新在Windo ...
- windows+caffe(四)——创建模型并编写配置文件+训练和测试
1.模型就用程序自带的caffenet模型,位置在 models/bvlc_reference_caffenet/文件夹下, 将需要的两个配置文件,复制到myfile文件夹内 2. 修改solver. ...
- caffe 无GPU 环境搭建
root@k-Lenovo:/home/k# sudo apt-get install libprotobuf-dev libleveldb-dev libsnappy-dev libopencv-d ...
随机推荐
- Django UrL 解析
Django的路由系统 URLconf 本质是URL与要为该URL调用的视图函数之间的映射表:你就是以这种方式告诉Django,对于客户端发来的某个URL调用哪一段逻辑代码对应执行. 1.1 djan ...
- 分布式锁实践(一)-Redis编程实现总结
写在最前面 我在之前总结幂等性的时候,写过一种分布式锁的实现,可惜当时没有真正应用过,着实的心虚啊.正好这段时间对这部分实践了一下,也算是对之前填坑了. 分布式锁按照网上的结论,大致分为三种:1.数据 ...
- uva-11234-表达式
后缀表达式,使用队列计算,要求计算的结果一样,输出队列的输入串 表达式转二叉树,层次序遍历,先右孩子,然后字符串反转输出 #include <iostream> #include < ...
- oracle忘记sys及system密码
一.忘记除SYS.SYSTEM用户之外的用户的登录密码. 用SYS (或SYSTEM)用户登录. CONN SYS/PASS_WORD AS SYSDBA; 使用如下语句修改用户的密码. ALTER ...
- 记录一些sql,怕忘了
SELECT business_line,count(*) FROM zc_db.t_bug group by business_line; 这个是展示的,显示某一项一共有多少个xxx,注意是grou ...
- MVC4 AspNet MVC下的Ajax / 使用微软提供的Ajax请求脚本 [jquery.unobtrusive-ajax.min.js]
源码参考:链接:http://pan.baidu.com/s/1pKhHHMj 密码:mkr4 1:新建-->项目-->Web-->ASP.NET MVC 4 Web 应用程序.命 ...
- C# 之 日常问题积累
https://www.cnblogs.com/xinaixia/p/3956349.html
- Spring Cloud Eureka高可用落地实战
一.原理 如图所示,多台Server端之间相互注册(这里以两台Server为例),Client端向所有的Server端注册. 二.Server端配置 1. 添加依赖 <dependency> ...
- SIEBEL GET最新时提示表异常
无法GET最新,则将此表GET一次,CHECK OUT下来,再UNDO CHECK IN即可
- 64. Minimum Path Sum (Graph; DP)
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which ...