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 ...
随机推荐
- Backing up the tail
The tail of the transaction log usually refers to the contents of the database's transaction log tha ...
- django-form.errors和前端上传文件
一.上传文件: 在相应的模型里面定义`FileField`或者是`ImageField`类型的字段,并且1.设置好`upload_to`参数来指定上传的路径. class User(models.Mo ...
- 517. Super Washing Machines
▶ 超级洗碗机.给定一个有 n 元素的整数数组,我们把 “将指定位置上元素的值减 1,同时其左侧或者右侧相邻元素的值加 1” 称为一次操作,每个回合内,可以选定任意 1 至 n 个位置进行独立的操作, ...
- Air21
handler package com.icil.edi.ws.milestoneService.handler; import java.text.SimpleDateFormat; import ...
- 小菜鸟入门nginx
实现功能:端口进行转发 比如我实际运行的是·http:localhost:5000 但是我想通过localhost:80 进行访问. 过程 1 下载nginx 2 解压到某个目录(比如我放在C盘根目录 ...
- java中将数字的字符串表示转化为数字
int a = new Integer("1234").intValue() 或 int b = Integer.parseInt("1234") System ...
- cluster DNS
[root@mhc1 dns]# pwd/root/test/k8s/kubernetes/cluster/addons/dns [root@mhc1 dns]# export DNS_SERVER_ ...
- for 续9
-------siwuxie095 for 拾遗: 一: for 语句里,do 后面一般会有括号,有括号就是复合语句, 假如需要用到括号里的变量,就需要 ...
- <!DOCTYPE html>的重要性!
噩梦开始的源头:之前写html或者jsp页面,从来不注意doctype的声明,也不太明白doctype的作用. 直到最近碰到了一个非常奇葩的bug:某一个页面在IE7和8,Chrome,ff等下正常, ...
- dedecms图片上传函数
/** * 图片上传类 * @param $file上传图片信息 * @param $ty */ function upload_pic($file, $ty) { if (!is_uploaded_ ...