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 ...
随机推荐
- javascript中数组的强大用法·
1 归并 var a = [{name: 'tom'},{name: 'aiscy'},{name: 'judy'},{name: 'mike'}];a.reduce(function(prev, i ...
- springboot 邮件服务
springboot仍然在狂速发展,才五个多月没有关注,现在看官网已经到1.5.3.RELEASE版本了.准备慢慢在写写springboot相关的文章,本篇文章使用springboot最新版本1.5. ...
- vuex语法精简(方便开发查阅)
vuex语法精简(方便开发查阅) store结构 state Getter Mutation actions vuex语法精简(方便开发查阅) 本文只是方便开发的时候快速查阅到相关语法,想看详细内容请 ...
- autocomplete.js的使用(2):自动输入时,出现下拉选择框
<!--自动输入文本值所需的jquery文件--><script src="/js/jquery-1.8.3.min.js" type="text/Ja ...
- $(function(){})理解
$(function(){}) = jQuery(function(){}) = jQuery(document).ready(function(){ });
- 使用 phpStorm 开发
苦恼蛋疼的曾哥工作室,让人痛不欲生,缓慢的同步速度,另人恼火的插件配置,让人疯狂的卡.简直是让人用了几天之后就不行了. 废话不多说,一款很好的php IDE. 1. phpStorm 下载 here ...
- oracle返回最大值一条记录
虽然网上例子很多,但是试过多种办法都无效,原代码出处: https://blog.csdn.net/qyshibb/article/details/73332075 这个例子简单有效 select p ...
- UNITY5 - fog
全局雾效在 window->lighting 的设置,可设置颜色和距离 注意摄像机的Rendering Path要选择Forward
- ssm 动态切换数据源
1,添加数据库配置 jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver #jdbc.url=jdbc:sqlserver://192.16 ...
- CentOS 6.5网络配置静态IP地址
打开VMvare,并进入虚拟机 2 输入用户名,按回车键,再输入密码,登录系统 3 进行网络配置前,需要确认几个事情: 1. 网络适配器模式是否为NAT模式 右键虚拟机,或者点击VMvare菜单栏中的 ...