VS2010的配置(设置编译环境)
1. 在python安装目录(如F:\Program Files\Python_3.5.3)下找到include和libs文件夹,将它们拷贝到sln同级目录下。
进入项目 > 属性 > 配置属性 > VC++目录 > 库目录,添加..\libs
进入项目 > 属性 > C/C++ > 常规 > 附加包含目录,添加..\include
C++代码
void DetactImage(CString image_name, CString model_path) { try{ Py_Initialize(); if (!Py_IsInitialized()) printf("Initialize Error!\n"); PyEval_InitThreads(); // 载入module PyObject * pModule = NULL; pModule = PyImport_ImportModule("demo");//调用的Python文件名 if (!pModule) { cout<<"cannot open module!"<<endl; Py_Finalize(); return; } // 将module中的方法以字典形式读入 PyObject *pDict = NULL; pDict = PyModule_GetDict(pModule); if (!pDict) { printf("PyModule_GetDict Error!\n"); return; } // 在方法字典中通过名字获取对应的方法 PyObject *pFunc = NULL; pFunc = PyDict_GetItemString(pDict, "image_detact"); if (!pFunc || !PyCallable_Check(pFunc)) { printf("Can't find function[image_detact]\n"); getchar(); return; } // 设置方法的参数 PyObject *pArgs = NULL; pArgs = PyTuple_New(2); PyTuple_SetItem(pArgs, 0, Py_BuildValue("s", image_name)); PyTuple_SetItem(pArgs, 1, Py_BuildValue("s", model_path)); //调用方法add,传入参数 float PyObject_CallObject(pFunc, pArgs); } catch(exception& e) { cout << "Standard exception: " << e.what() << endl; } }
Python代码
import cv2 import matplotlib.pyplot as plt import tensorflow as tf def image_detact(image_name, model_path): print (image_name) print (model_path) im = cv2.imread(image_name) cv2.imshow('image', im) cv2.waitKey(0) ...