在c++中运行经过训练的keras模型

running a trained keras model in c++

本文关键字:keras 模型 经过 c++ 运行      更新时间:2023-10-16

我在keras中训练了一个多层感知器,将模型序列化为JSON,并将权重保存为HDF5。我如何在C/C++中导入这个模型来对它进行一些预测?

就在C++中运行Keras模型而言,

frugally deep似乎拥有最多的功能。它支持比keras2cpp更多的几个模型体系结构。

这应该完全符合您的要求。

使用

节省网络权重和架构。

使用Dump_to_imple_cpp.py脚本将网络结构转储到纯文本文件中。

使用带有keras_model.h和keras_mode.cc 代码的网络

请参阅下面链接的github以获取更多信息。

keras2cpp

两步-

  1. 将Keras模型保存到python中的文本文件中
  2. 在C++中,读取这些文本文件,并在多线程环境中运行模型

以上步骤的详细信息

  1. 第一步,从Github-上的keras2cpp.py调用save_keras_model_as_text

    save_keras_model_as_text(模型,打开('/content/modeltext.txt','w'((

    save_keras_model_as_text(模型,打开('/content/modellayersonlytext.txt','w'(,noweight=True(

  2. 在c++项目中,包括keras.h/keras.cpp文件。

  3. 将输入图像转换为Keras格式或从文件中将输入图像读取为Keras形式。

''

//assume dst is pointer to an image object. This 
//can be of CxImage / CImg /OpenCV or of any other 
//library.
int h = dst->GetHeight();
int w= dst->GetWidth();;

int *img = new int[h*w*3];
int *img_r = img, *img_g =&img[h*w], *img_b=&img[2*h*w];


for (int y = 0; y < h; y++) {
for (int x = 0; x < w;x++) {
RGBQUAD rgb= dst->GetPixelColor(x,y);
*img_r= rgb.rgbRed; img_r++;
*img_g= rgb.rgbGreen; img_g++; 
*img_b = rgb.rgbBlue; img_b++;

}

}

''

  1. 调用ExecuteKerasSegmentation。

    ''

    //text files in which keras model is saved.
    char *modelfile ="modellayersonlytext.txt";  
    char *weightfile="modeltext.txt";
    int *result = ExecuteKerasSegmentation(img, h, w, 3, modelfile, weightfile);
    

    ''

  2. result包含分割结果。您可以将其保存到pgm文件中,也可以将其转换为图像库对象并进一步使用。

''

save_image_pgm("segmentation_map.pgm",result,h,w,127); //127 is scaling factor for binary images.

''