Search code examples
c++templatesopencvtype-traits

type traits for OpenCV data types


I have a template method in which a Mat object is constructed. The type of this matrix depends on the template implementation:

template <typename T>
void createMatrixAndDoStuff(int rows, int cols){
// ...
Mat A(rows,cols,getCVtype<T>::value);
// ...
}

In this case I use a basic trait, getCVType<T>::value will return CV_32F if T=float, etc. I know this is silly, because I could have used Mat_<T>(rows,cols) and forget about using traits for this. But it made me think: is there any available trait (or any template stuff) in OpenCV to infer type macros (CV_32F,CV_8U,...) in compile time from types?


Solution

  • opencv do have the type traits for this task, it called cv::DataType, you do not need to create one by yourself

    static_assert(cv::DataType<float>::type == CV_32F, 
                  "cv::DataType<float>::type == CV_32F");
    static_assert(cv::DataType<uchar>::type == CV_8U, 
                  "cv::DataType<uchar>::type == CV_8U");
    static_assert(cv::DataType<cv::Vec3b>::type == CV_8UC3, 
                  "cv::DataType<cv::Vec3b>::type == CV_8UC3");