Boyko Perfanov
Boyko Perfanov

Reputation: 3047

How to generate a cv::Mat type code?

I've been using the c-style api to generate opencv type codes. For example:

cv::Mat(h, w, CV_8UC2);

CV_8UC2 is a macro defined in types_c.h (deprecated?):

#define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT))

Is there a similar type code generation function in the c++ api, something like

Mat m(w,h, cv::Type(Vec<unsigned char, 2>).typecode()) ?

Upvotes: 0

Views: 796

Answers (1)

Яois
Яois

Reputation: 3858

As I said in my comments, CV_MAKETYPE is not deprecated, and afaik it is the standard way of generating those "type codes".

However (and just for fun), an alternative, more C++-ish, way of generating arbitrary codes (still in compile time) can be achieved by using TMP...

template <int depth,
          int cn>
struct make_type
{
    enum {
       // (yes, it is exactly the same expression used by CV_MAKETYPE)
       value = ((depth) & CV_MAT_DEPTH_MASK) + (((cn)-1) << CV_CN_SHIFT)
    };
};

// You can check that it works exactly the same as good, old `CV_MAKETYPE`     
cout << make_type<CV_8U,2>::value << " "<< CV_MAKETYPE(CV_8U,2) << endl;

... but don't do this. While tmp is fun and amazing, CV_MAKETYPE is the right way of doing things in this case.

EDIT: OpenCV has its own type traits utilities. In core/traits.hpp we can find class DataType:

The DataType class is basically used to provide a description of ... primitive data types without adding any fields or methods to the corresponding classes (and it is actually impossible to add anything to primitive C/C++ data types). This technique is known in C++ as class traits. It is not DataType itself that is used but its specialized versions ... The main purpose of this class is to convert compilation-time type information to an OpenCV-compatible data type identifier ...

So, such traits are used to tell OpenCV which data type you are working with, even if such a type is not native to OpenCV.

Upvotes: 2

Related Questions