Welcome to the keras2cpp multithreading image segmentation wiki!
Train your image segmentation model in keras and then Convert your keras model into C / C++ /vc++ with multithreading to use directly with your c/c++ program. Very easy to use. Only contains 3 files
1. keras2cpp.py - python code to convert your keras model into two text files
2. keras.cpp and keras.h files to include it into your c/c++ program and inference your model.
Keras2cpp.py - just import or copy and paste the function - save_keras_model_as_text .....
from keras2cpp import *
#load model
model=keras.models.load_model('mymodel.h5')
#save model into two text files
save_keras_model_as_text(model, open('modeltext.txt', 'w') )
`save_keras_model_as_text(model, open('modellayersonlytext.txt', 'w') , noweight=True)``
Now, Inference model into c/c++
include "Keras.h" file
read an image and convert it into keras format. In example file, we read a ppm image in keras format. If we are using a library like opencv, cximage, cimg etc.. we convert image into our keras format.
a sample code below -
unsigned int r,g,b;
int *img = new int[h*w*3];
int *img_r = img, *img_g =&img[h*w], *img_b=&img[2*h*w];
`int k=0;`
`for (int y = 0; y < h; y++) {`
`for (int x = 0; x < w;x++) {`
`read r, g, b`
`*img_r++ =r; *img_g++ =g; *img_b++ = b;`
`}`
`}`
char *modelfile ="C:\\bcrpath\\modellayersonlytext.txt";
char *weightfile="C:\\bcrpath\\modeltext.txt";
int *result = ExecuteKerasSegmentation(img, h, w, 3, modelfile, weightfile);
`delete img;`
`if(result==NULL)`
`{`
`AfxMessageBox("Keras error returned null");`
`return;`
`}`
`save_image_pgm("C:\\bcrpath\\segmentation_map.pgm",result,h,w,127);`
the result is a 1d array of 0s and 1s which store segmentation map. The value at 2D point (x,y) can be accessed as result[y*w+x]. In above code, we are saving result in an image file (pgm). For any library, we can use their setpixelcolor/setpixel functions in loop or createfromarray function to convert this array into that library object.
Note - Irfanview can display ppm /pgm image files.