How can I get the value type for a cv::Mat?

asked 2018-06-04 10:24:10 -0500

sage gravatar image

updated 2018-06-04 10:36:22 -0500

berak gravatar image

I'm trying to get the value type for an element of my matrix and avoid having to hardcode it in order to maximize portability and compatibility with possible future changes.

The obvious way for me would seem to use TypeDepth::value_type as defined in traits.cpp (located here: https://github.com/opencv/opencv/blob...)

Unfortunately the value_type member is defined as private, which I don't quite understand. Is there another way to access this?

To clarify with an example, I'm trying to do something like this:

using Type16S = cv::TypeDepth<CV_16S>::value_type;

In order to use the new type defenition in such a way:

cv::Mat matrix(10,10, CV_16S)
Type16S* pointer = matrix.ptr<Type16S>(1);
edit retag flag offensive close merge delete

Comments

and compatibility with possible future changes.

seen this ? (you should not use DepthType at all)

can you explain your use-case ?

and avoid having to hardcode it

those templates have to be valid at compile time, so one way or the other you have to hardcode it

berak gravatar imageberak ( 2018-06-04 10:39:10 -0500 )edit

Thanks for your reply.

My thinking was, that ideally I could use this every time I use pointers to matrix elements. So instead of explicitly specifying e.g. float, I would only have to specify CV_32F, and the underlying datatype is then determined by the openCV code.

Of course the CV type has to be hardcoded, but I'm trying to avoid having to specify the underlying datatype again, since that might vary from system to system or over time. It might not, but in my view this would be a much cleaner solution.

Another use-case would be to write my own templated functions that take the openCV-type as template argument. Of course I could (and have done so in the past) hardcode the corresponding types again, but IMHO that's not a very clean solution and should be in the openCV code, not mine.

sage gravatar imagesage ( 2018-06-04 11:46:04 -0500 )edit

my own templated functions

that's usually the solution. at some point you still have to fill in the type , but you could save a lot of boiler plate code like:

template<class T>
void someFunction(int w, int h) {
    cv::Mat matrix(h, w, DataType<T>::type)
    T* pointer = matrix.ptr<T>(1);
}

(it just works "the other way round", than you tried)

((also noone can or will stop you from inventing your own traits system !!))

berak gravatar imageberak ( 2018-06-04 11:59:10 -0500 )edit