将图像数据从python传递到c ++中的cv :: mat

时间:2018-08-14 05:43:51

标签: python numpy c++11 pybind11 opencv-mat

我正在从我的python接口读取图像为cv2.imread(“ abc.tiff”,1),我想将此图像传递给由pybind11绑定的c ++函数。 C ++函数需要cv :: Mat作为输入。

现在我了解到python将其转换为NxM 3D数组NumPY

我发现数据的高度,宽度和通道分别为5504 8256 3。

任何帮助我如何找到解决方案的人。


同样,我需要将cv :: Mat传递给Python接口

1 个答案:

答案 0 :(得分:0)

对于python numpy -> c++ cv2,我找到了一种通过本地python扩展模块进行操作的方法。

python3

image = cv.imread("someimage.jpg", 1)
dims = image.shape
image = image.ravel()
cppextenionmodule.np_to_mat(dims, image)

c ++

static PyObject *np_to_mat(PyObject *self, PyObject *args){
    PyObject *size;
    PyArrayObject *image;

    if (!PyArg_ParseTuple(args, "O!O!", &PyTuple_Type, &size, &PyArray_Type, &image)) {
        return NULL;
    }
    int rows = PyLong_AsLong(PyTuple_GetItem(size ,0));
    int cols = PyLong_AsLong(PyTuple_GetItem(size ,1));
    int nchannels = PyLong_AsLong(PyTuple_GetItem(size ,2));
    char my_arr[rows * nchannels * cols];

    for(size_t length = 0; length<(rows * nchannels * cols); length++){
        my_arr[length] = (*(char *)PyArray_GETPTR1(image, length));
    }

    cv::Mat my_img = cv::Mat(cv::Size(cols, rows), CV_8UC3, &my_arr);

    ...
}

您可以检查boost python包装器解决方案link

详细了解扩展模块link

通过python扩展模块link

了解有关numpy的更多信息