我试图使用嵌入在C程序中的
Python 3.5解释器从C接收图像,并将其用作我训练的张量流模型的输入.首先,我将我的图像转换为numpy数组,然后将其发送到python.这是我的简化代码,工作正常(从
here采用的代码):
Python代码:
def multiply_fun(M):
V = M*2
print(V)
我的C代码调用上面的函数:
#include
#include
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include
#include
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 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:
Traceback (most recent call last):
File "C:\Users\Matin\Anaconda3\Lib\threading.py", line 1283, in _shutdown
assert tlock.locked()
SystemError: returned a result with an error set
谢谢你的帮助.
编辑1:
通过从skimage.io导入imsave移动到python函数之外(如评论中建议的@moooeeeep),我在此行中获得Null:
PyObject* python_code = PyImport_ImportModule("python_code");