简体   繁体   中英

pass image data from python to cv::mat in c++

I am reading an image as cv2.imread("abc.tiff",1) from my python interface, I want to pass this to c++ function which is binded by pybind11. The C++ function requires a cv::Mat as input.

Now I learned that python transforms that to NumPY , a NxM 3D array

I find the data height, width, channels as 5504 8256 3 respectively.

Any help me how do I find the solution for it.


Same again I need to pass a cv::Mat to Python interface

For the python numpy -> c++ cv2 I found a way how to do it via native python extension module.

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);

    ...
}

you can check the boost python wrapper solution link

read more about extension module link

read more about numpy via python extension modulelink

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM