Home > Enterprise >  C type from dtype (how to initialize a cv::Mat from a numpy array)
C type from dtype (how to initialize a cv::Mat from a numpy array)

Time:06-28

pybind11 has the following method in numpy.h:

    /// Return dtype associated with a C   type.
    template <typename T>
    static dtype of() {
        return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::dtype();
    }

How do I get the inverse? the C type from a variable of type dtype ?

EDIT

My original problem is that I want to bring an OpenCV image from python to c as described here, note that the cast done in this answer is always of type unsigned char*:

cv::Mat img2(rows, cols, type, (unsigned char*)img.data());

What I want to do is to use .dtype() to get the "python type" and then do the right cast.

Because of this, my function signature takes an py::array as parameter.

int cpp_callback1(py::array& img)
{
//stuff
cv::Mat img2(rows, cols, type, (unsigned char*)img.data());
                                ^^^ Somehow I want this to be variable
//more stuff

}

Maybe I can get the type_id from my dtype?

CodePudding user response:

cv::Mat has a constructor that accepts a void* for the data pointer.

Therefore you don't need to convert the dtype into a C type.
You can simply use:

cv::Mat img2(rows, cols, type, (void*)img.data());
  • Related