目錄
-
- 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相關運作時檔案
待完善,歡迎交流