C + + calls Tensorflow model in Python

Keywords: Programming Python Session Ubuntu cmake

C + + calls Tensorflow model


Use C + + to call Python 2.7 program, load tensorflow model (why not use Python 3, there are too many pits, which has not been solved well). The whole environment is completed under Ubuntu 16.04, using kDevelop4 IDE to write c + + program and cmake file.

Save tensorflow model

First, write a piece of tensorflow code to save the model in Python:

import tensorflow as tf
import os

def save_model_ckpt(ckpt_file_path):
    x = tf.placeholder(tf.int32,name='x')
    y = tf.placeholder(tf.int32,name='y')
    b = tf.Variable(1,name='b')
    xy = tf.multiply(x,y)
    op = tf.add(xy,b,name='op_to_store')
    sess = tf.Session()
    sess.run(tf.global_variables_initializer())

    path = os.path.dirname(os.path.abspath(ckpt_file_path))
    if os.path.isdir(path) is False:
        os.makedirs(path)

    tf.train.Saver().save(sess,ckpt_file_path)

    feed_dict = {x:4,y:3}
    print(sess.run(op,feed_dict))

save_model_ckpt('./model/model.ckpt')

This will save four files back in the model directory

Model loading code

#classify.py
import tensorflow as tf

def evaluate(pic):  
    sess = tf.Session()
    saver = tf.train.import_meta_graph('/home/tyl/Code/Kprojects/cpython/Test/model/model.ckpt.meta')
    saver.restore(sess, tf.train.latest_checkpoint('../model'))
    print(type(sess.run('b:0')))
    input_x = sess.graph.get_tensor_by_name('x:0')
    input_y = sess.graph.get_tensor_by_name('y:0')
    op = sess.graph.get_tensor_by_name('op_to_store:0')
    add_on_op = tf.multiply(op,2)
    ret = sess.run(add_on_op,{input_x:5,input_y:5})
    print ret
    sess.close()
    return pic

Note here that the model loading path must be correct....

C + + program calls Python program

Here, use C + + program to call Python program loaded by model

//readTF.cpp
#include <Python.h>
#include <pythonrun.h>
#include <iostream>
#include <string.h>

int main()
{
  const int flag= 1;
  Py_Initialize();
  if (!Py_IsInitialized())
  {
    return -1;
  }

  PyRun_SimpleString("import sys");
  //The path must be right
  PyRun_SimpleString("sys.path.append('/home/tyl/Code/Kprojects/cpython/Test')");
  
  PyObject* pMod = NULL;
  PyObject* pFunc = NULL;
  PyObject* pParm = NULL;
  PyObject* pRetVal = NULL;
  int iRetVal=999;
  PyObject* pName = PyString_FromString("classify");
  pMod = PyImport_Import(pName);//Acquisition module
  if (!pMod)
  {
	std::cout << pMod <<std::endl;
    return -1;
  }
  const char* funcName = "evaluate";
  pFunc = PyObject_GetAttrString(pMod,funcName);//Get function
  if (!pFunc)
  {
    std::cout << "pFunc error" <<std::endl;
    return -1;
  }
  
  pParm = PyTuple_New(1);//New tuple
  PyTuple_SetItem(pParm, 0, Py_BuildValue("i",flag));//Pass parameters to Python module
  pRetVal = PyObject_CallObject(pFunc,pParm);//Get return results

  PyArg_Parse(pRetVal,"i",&iRetVal);//Parse into the form required by C + +
  std::cout<< iRetVal <<std::endl;
  return 0;
}

CMakeLists document writing

cmake_minimum_required(VERSION 2.6)
project(test)
set (CMAKE_BUILD_TYPE Debug)
set (CMAKE_CXX_FLAGS "-std=c++11")

include_directories( /usr/include/python2.7)		    
add_executable(readTF readTF.cpp)
target_link_libraries(readTF -lpython2.7)

Result

Results of running on KDevelop4

Posted by ojeffery on Wed, 11 Dec 2019 08:05:09 -0800