How can convert PyObject variable to Mat in c++ opencv code

后端 未结 3 663
不思量自难忘°
不思量自难忘° 2021-01-27 08:59

I have a c++ facerecognition code and a python code in opencv. In python code i read frames from a robot and i want to send this fram to my c++ code. I use this link tho call p

相关标签:
3条回答
  • 2021-01-27 09:34

    Since showNaoImage returns a numpy array, you can use numpy's C API to extract values from the frame, or obtain the pointer to the memory that holds the values. See the documentation, specifically the part that deals with array data access.

    To convert the data to a Mat array accepted by cv::imshow, use the Mat constructor with the data and its dimensions. For example:

    // numpy array created from a PIL image is 3-dimensional:
    // height x width x num_channels (num_channels being 3 for RGB)
    assert (PyArray_NDIM(presult) == 3 && PyArray_SHAPE(presult)[2] == 3);
    
    // Extract the metainformation and the data.
    int rows = PyArray_SHAPE(presult)[0];
    int cols = PyArray_SHAPE(presult)[1];
    void *frame_data = PyArray_DATA(presult);
    
    // Construct the Mat object and use it.
    Mat cv_frame(rows, cols, CV_8UC3, frame_data);
    cv::imshow("Original_image", cv_frame);
    
    0 讨论(0)
  • 2021-01-27 09:35

    If I remember correctly, there should be a specific function available in opencv for python called pyopencv_to(pyobject, cv::mat, ... ), which also takes strides into the account and can handle both gray and color images.

    0 讨论(0)
  • 2021-01-27 09:39

    For Python 3.x C-API:

    In Python side return the frame in bytearray format:

    return bytearray(frame)
    

    and in cpp side get it by PyByteArray_AsString function:

    pData = PyObject_CallObject(pFunc, pArgs);
    uchar *data = (uchar *)PyByteArray_AsString(pData );
    cv::Mat img(rows, cols, CV_8UC3, data)
    
    0 讨论(0)
提交回复
热议问题