Convert between depth values and depth types
Does OpenCV have some compile-time way to convert between depth values and depth types?
cv::Mat
has several template based methods like at<>
which require a type at compile-time.
OpenCV usually uses depth types as values, e.g. CV_8U
and CV_32f
.
Such a utility comes in handy when using such methods to provide generic implementations.
I wrote my own, but was wondering, is there already such a tool?
Just in case, here's my code:
opencv_depth_to_type.h
:
#ifndef opencv_depth_to_type_h__
#define opencv_depth_to_type_h__
#include <cv.h>
template <int Depth>
struct DepthToType
{};
// Template specializations for: CV_8U, CV_8S, CV_16U, CV_16S, CV_32S, CV_32F, CV_64F
template <> struct DepthToType<CV_8U > { typedef unsigned char depth_type; };
template <> struct DepthToType<CV_8S > { typedef signed char depth_type; };
template <> struct DepthToType<CV_16U> { typedef unsigned short depth_type; };
template <> struct DepthToType<CV_16S> { typedef signed short depth_type; };
template <> struct DepthToType<CV_32S> { typedef signed int depth_type; };
template <> struct DepthToType<CV_32F> { typedef float depth_type; };
template <> struct DepthToType<CV_64F> { typedef double depth_type; };
#endif // opencv_depth_to_type_h__
You use it like this:
template <int Depth> // Depth is a depth value known AT COMPILE-TIME
void myTemplateFunc()
{
// At RUN time, allocate image of correct type using the VALUE Depth
cv::Mat img(cv::Size(10,10), CV_MAKETYPE(Depth,1));
// ...
// Access pixel with correct and generic depth - specified at COMPILE time
// (must use typename to specify the type name depth_type)
img.at< typename DepthToType<Depth>::depth_type >(cv::Point(5,5)) = 7;
// ...
}
It is, just forgot its name...
Looking at @Vladislav Vinogradov's answer below this can be extended to support channel number as well by using
Vecxy
specializations.