天天看点

Windows:C++调用python文件调用keras模型推理

目录

    • Step1:Python文件
    • Step2:C++文件
    • Step3:编译python相关运行时文件

Step1:Python文件

from tensorflow.keras.models import load_model
import cv2 as cv
import numpy as np

def create_classifier(model_path):
    model = load_model(model_path)
    return model

def model_predict(model,image_path):
    img = cv.imread(image_path)
    img = cv.resize(img, (224,224))
    image = np.expand_dims(img,axis=0)
    result = model.predict(image)
    print(result)
    return result
           

Step2:C++文件

#include<iostream>
#include <Python.h>
#include<windows.h>
#include<time.h>
using namespace std;

//Python模型加载初始化
PyObject* create_classifier(PyObject* module, char* model_path)
{
	//PyEval_InitThreads();
	//initialize the classifier
	PyObject* pArgs_model_path = Py_BuildValue("(s)", model_path);
	//Python文件中的函数名
	PyObject* pFunc1 = PyObject_GetAttrString(module, "create_classifier");  
	//call fuction1 to create model
	PyObject* model = PyObject_CallObject(pFunc1, pArgs_model_path);
	//Py_Finalize();
	return model;
}
//推理过程
PyObject* predict_result(PyObject* module,PyObject* model, char* image_path)
{
	//classification fuction
	PyObject * pyParams = PyTuple_New(2);
	PyTuple_SetItem(pyParams, 0, model);//the first param
	PyTuple_SetItem(pyParams, 1, Py_BuildValue("s", image_path));//the second param
	PyObject* pFunc2 = PyObject_GetAttrString(module, "model_predict");
	//call fuction to predict
	PyObject* result = PyObject_CallObject(pFunc2, pyParams);
	return result;
}

//在主函数中测试推理过程
int main()
{
	char* image_path1 = "test.jpg";
	char* image_path2 = "test2.jpg";
	char* image_path3 = "1_0.jpg";
	char* image_path4 = "2_0.jpg";
	char* model_path = "model.h5";

	Py_SetPythonHome(L"D:/Python37");
	Py_Initialize();
	PyRun_SimpleString("import sys");
	PyRun_SimpleString("sys.path.append('./')");

	//myModel:Python文件名,无需加文件后缀
	PyObject* module = PyImport_ImportModule("predict");
	if (!module) {
		printf("cannot open module!");
		Py_Finalize();
		return -1;
	}

	PyObject* mymodel = create_classifier(module,model_path);
	PyObject* result = NULL;
	result = predict_result(module, mymodel, image_path1);
	cout << result << endl;

	Py_Finalize();
	system("pause");
	return 0;
}
           

Step3:编译python相关运行时文件

待完善,欢迎交流