我正在尝试使用嵌入到C++程序中的Python3.5解释器来接收来自C++的图像,并将其用作我训练的tensorflow模型的输入。首先,我将图像转换为numpy数组,然后将其发送到python。这是我的简化代码,运行良好(代码取自here):
Python代码:
def multiply_fun(M):
V = M*2
print(V)
调用上述函数的C++代码:
#include <Python.h>
#include <abstract.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <ndarrayobject.h>
#include <vector>
int main()
{
Py_InitializeEx(1);
PyObject* sysPath = PySys_GetObject((char*)"path");
PyObject* curDir = PyUnicode_FromString(".");
PyList_Append(sysPath, curDir);
Py_DECREF(curDir);
PyObject* python_code = PyImport_ImportModule("python_code");
PyObject* multiply_fun = PyObject_GetAttrString(python_code, "multiply_fun");
Py_XDECREF(python_code);
import_array1(-1);
npy_intp dim[] = { 5, 5 };
std::vector<double> buffer(5*5, 1);
PyObject* array_2d = PyArray_SimpleNewFromData(2, dim, NPY_DOUBLE, &buffer[0]);
PyObject* return_value1 = PyObject_CallFunction(multiply_fun, "O", array_2d);
Py_XDECREF(return_value1);
Py_XDECREF(array_2d);
Py_XDECREF(multiply_fun);
Py_Finalize();
return 0;
}
然而,当我想要使用大多数python库时,我得到了一个错误。例如,对于以下python代码:
def multiply_fun(M):
from skimage.io import imsave
imsave('test.png', M)
我得到了这个错误:
Exception ignored in: <module 'threading' from 'C:\\Users\\Matin\\Anaconda3\\Lib\\threading.py'>
Traceback (most recent call last):
File "C:\Users\Matin\Anaconda3\Lib\threading.py", line 1283, in _shutdown
assert tlock.locked()
SystemError: <built-in method locked of _thread.lock object at 0x0000000002AF4418> returned a result with an error set
顺便说一句,This related discussion帮不了我。
谢谢你的帮助。
EDIT 1:通过将from skimage.io import imsave
移到python函数的外部(正如@moooeeeep在注释中建议的那样),我在下面的代码行中得到了Null:
PyObject* python_code = PyImport_ImportModule("python_code");
发布于 2017-09-13 14:36:16
问题似乎在于,在使用from package.submodule import function
时,PyImport_ImportModule
无法加载某些包的子模块。它已经在Python/C API Reference Manual中解释过了
如果name参数包含一个点(当它指定包的子模块时),则将fromlist参数设置为列表'*‘,以便返回值是已命名模块,而不是包含该模块的顶级包。(不幸的是,当name实际上指定的是子包而不是子模块时,这会产生额外的副作用:加载在包的all变量中指定的子模块。)返回对导入模块的新引用,或在失败时返回NULL并设置异常。模块导入失败不会将模块留在sys.modules中。
此函数始终使用绝对导入。
https://stackoverflow.com/questions/46169650
复制相似问题