我正在构建 NIST FRVT11 库。我有 python 核心代码,我想从 c++ 调用它,我已经按照官方 Python C API 文档在 c++ 中使用 python 函数。
我可以在初始化阶段使用 keras 模型加载和预测一次。但在
model.predict
函数花费无限时间之后,无法从同一模型进行预测。
我什至无法加载模型,这次tf.keras.models.load_model
需要无限的时间。
我没有收到任何可以粘贴到此处的错误:(
NIST 希望所有内容都打包在库中,因此我在本地构建了 python 并将其附加到提交中。
Python:3.9.13 张量流:2.8.0 喀拉斯:2.8.0
Python代码
import tensorflow as tf
def get_model(model_path):
embedding_model = tf.keras.models.load_model(model_path)
return embedding_model
def predict(model, img):
out= model.predict(img)
return out
c++代码
int call_python_code(const std::string &configDir)
{
this->configDir = configDir;
// add directory to sys path
std::string command_sys_path_to_append = "import sys, os\n"
"sys.path.append(os.path.join(os.getcwd(), '" + this-
>configDir + "'))\n";
PyRun_SimpleString(command_sys_path_to_append.c_str());
Py_Initialize();
PyObject *p_module_name = PyUnicode_DecodeFSDefault("fr"); // fr.py file
this->p_module = PyImport_Import(p_module_name);
// load the model from c++
PyObject *outer_tuple_2 = PyTuple_New(1);
PyTuple_SetItem(outer_tuple_2, 0, PyUnicode_DecodeFSDefault(this->configDir.c_str()));
PyObject *p_fucntion_model = PyObject_GetAttrString(p_module, "get_model");
this->p_embedding_model_object = PyObject_CallObject(p_fucntion_model, outer_tuple_2);
// get prediction
PyObject *p_function_predict= PyObject_GetAttrString(p_module, "predict");
PyObject *full_args = PyTuple_New(2);
PyTuple_SetItem(full_args, 0, this->p_fucntion_model);
PyTuple_SetItem(full_args, 1, <image array>);
PyObject *outer_tuple = PyTuple_New(1);
PyTuple_SetItem(outer_tuple, 0, full_args);
PyObject *p_return_tuple = PyObject_CallObject(p_function_predict, outer_tuple);
}
@Nawal 你能让它发挥作用吗?