-1

我正在尝试将图像从 C 传递到 python 并将数组从 python 传递回 C 并获取其中的长度和数据。这是我的 Python 代码:

def detect(pI,col,row,channels):
    I_reshape = np.asarray(list(pI), dtype=np.ubyte)
    I_reshape = np.reshape(I_reshape,(row,col,channels))
    cv2.imshow("testWin",I_reshape)
    cv2.waitKey(0)

    a = np.arange(4).reshape((2, 2))
    return a;

这是我的 C 代码:

#include <python.h>
#include <direct.h>
#include <opencv2\opencv.hpp>
#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <stdio.h>

using namespace std;

int main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pFunc;
    PyObject *pArgs, *pArg, *pResult;

    Py_Initialize();
    pName = PyUnicode_DecodeFSDefault("getArray");
    pModule = PyImport_Import(pName);
    Py_DECREF(pName);
    pFunc = PyObject_GetAttrString(pModule, "returnArray");
    pArgs = PyTuple_New(4);
    pArg = PyByteArray_FromStringAndSize((char*)img.data, img.total() * img.elemSize());
    PyTuple_SetItem(pArgs, 0, pArg);
    PyTuple_SetItem(pArgs, 1, PyLong_FromLong(img.cols));
    PyTuple_SetItem(pArgs, 2, PyLong_FromLong(img.rows));
    PyTuple_SetItem(pArgs, 3, PyLong_FromLong(img.channels()));
    pResult = PyObject_CallObject(pFunc, pArgs);

    int SIZE = PyByteArray_Size(pResult);
    Py_XDECREF(pResult);
    uint *data = (uint *)PyByteArray_AsString(pResult);
    Py_XDECREF(pResult);

    printf("Return of call (size): %d\n", SIZE/sizeof(uint)); 
    printf("Return of call (data): %d\n", data[0]);

    Py_DECREF(pResult);
    return 0;
}

问题是我得到了正确的大小,但我的数据只得到零。我哪里错了?

4

1 回答 1

0

我通过使用 Lists 作为 C 的返回参数解决了我的问题。如果你list()的返回值,它会正常工作:

a = np.array([[1.1,1.2],[2.1,2.2],[3.1,3.2],[4.1,4.2]]).reshape(8,1);
return list(a);

然后在C中,我这样做:

int main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pFunc;
    PyObject *pArgs, *pArg, *pResult;
    int i = 0, j = 0;

    cv::Mat img;
    img = cv::imread("..\\..\\x64\\Release\\1.jpg",1);

    Py_Initialize();
    pName = PyUnicode_DecodeFSDefault("showImage");
    pModule = PyImport_Import(pName);
    Py_DECREF(pName);
    pFunc = PyObject_GetAttrString(pModule, "detect");

    pArgs = PyTuple_New(4);
    pArg = PyByteArray_FromStringAndSize((char*)img.data, img.total() * img.elemSize());
    PyTuple_SetItem(pArgs, 0, pArg);
    PyTuple_SetItem(pArgs, 1, PyLong_FromLong(img.cols));
    PyTuple_SetItem(pArgs, 2, PyLong_FromLong(img.rows));
    PyTuple_SetItem(pArgs, 3, PyLong_FromLong(img.channels()));

    pResult = PyObject_CallObject(pFunc, pArgs);
    Py_DECREF(pArgs);

    if (PyList_Check(pResult)) {
        int SIZE = PyList_Size(pResult);
        float *arr = new float(SIZE);
        for (i = 0; i < SIZE; i++) arr[i] = PyFloat_AsDouble(PyList_GetItem(pResult, i));

        for (i = 0; i < SIZE / 2; i++) {
            for (j = 0; j < 2; j++) {
                printf("%f, ", arr[i * 2 + j]);
            }
            printf("\n");
        }
    }

    return 0;
}

其中最后 14 行获取返回的列表并提取其项目。

于 2019-03-07T09:50:55.217 回答