0

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?

wohlstad
  • 12,661
  • 10
  • 26
  • 39
Ivan
  • 1,352
  • 2
  • 13
  • 31
  • 2
    You cannot "get the C++ type" from a runtime value. It doesn't make any sense. What does "get the C++ type" ever mean? – n. m. could be an AI Jun 27 '22 at 14:55
  • `decltype(var)` gives you a type of `var`. – Askold Ilvento Jun 27 '22 at 14:56
  • @AskoldIlvento but what type should the requested function return ? It has to be known at compile time, and cannot depend on a run time value. – wohlstad Jun 27 '22 at 14:57
  • @n.1.8e9-where's-my-sharem. you are right, I didn't think it that deep while writting the question, I added an **EDIT** to clarify what I actually need. – Ivan Jun 27 '22 at 15:05
  • 1
    @Ivan the constructor of `cv::Mat` accepts a `void*`. Why do you need to cast your data pointer to a specific type ? – wohlstad Jun 27 '22 at 15:08
  • @wohlstad I hadn't considered `void *` I thought it wouldn't work as they cast in the question I quoted, I'll test – Ivan Jun 27 '22 at 15:09
  • 1
    It should work assuming you use this constructor: https://docs.opencv.org/4.x/d3/d63/classcv_1_1Mat.html#a51615ebf17a64c968df0bf49b4de6a3a. – wohlstad Jun 27 '22 at 15:11
  • @wohlstad you are very right, thanks!! you may want to write it in detail as an answer :) – Ivan Jun 27 '22 at 15:14
  • Wrote an answer (similar to my comment), so the post can be "finalized". – wohlstad Jun 27 '22 at 16:14

1 Answers1

2

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());
wohlstad
  • 12,661
  • 10
  • 26
  • 39