我需要从 openCV 获取数据类型 Mat键入并稍后在显式实例化的类中使用它:
template class Tensor<float>;
template class Tensor<uint16_t>;
template class Tensor<int8_t>;
我只能访问 C++11 并且不允许使用 boost,所以这样的事情是不可能的:
std::map<int, std::any> cvToTypeMap = {{CV_32F, float}, //std::any <- C++17
{CV_16U, uint16_t},
{CV_8S, int8_t}};
Tensor<cvToTypeMap[my_cv_mat.type()]> my_class_var(...);
如您所见,问题是我的 map 中需要这种不同的类型。
如果我没记错的话,我也不能使用 decltype(*my_cv_mat.data)
,因为它是 uchar
。
现在有什么想法可以实现这一目标吗?
最佳答案
与其尝试拥有类型映射,不如拥有 worker 映射并编码 int
手动到数字类型映射。然后我们需要一个张量构建器,它将采用 cv::Mat
创建适当的张量对象。
您必须编写如下特征:
template <int CVType>
struct int_to_numeric_type;
template <> struct int_to_numeric_type<CV_32F> { using type = float; };
template <> struct int_to_numeric_type<CV_16U> { using type = uint16_t; };
// ...
template <int CVType>
struct tensor_type {
using type = Tensor<
typename int_to_numeric_type<CVType>::type
>;
};
一旦完成,张量生成器就可以像这样计算出来:
template <int CVType>
struct TensorBuilder {
std::reference_wrapper<cv::Mat const> mat;
TensorBuilder(cv::Mat const& matrix) : mat(matrix) {}
typename tensor_type<CVType>::type make_tensor(/*Stuff other than matrix*/) const {
// Extract all the stuff from mat you need and perform the numeric logic here
return typename tensor_type<CVType>::type(...);
}
};
现在,我们的张量构建器可以从 cv::Mat
隐式构建对象,我们将与 std::function
一起滥用它.让我们来看看 worker :
template <int CVType>
void do_work(TensorBuilder<CVType> builder /*, ... */) {
auto tensor = builder.make_tensor();
// Do whatever you fancy with your tensor (ie, that's the body of your actual function)
}
然后,我们可以将这些 worker 嵌入到 std::function<void(cv::Mat const&/*, ...*/)>
的 map 中!
std::map<int, std::function<void(cv::Mat const& /*,...*/)> > workerMap {
{CV_32F, &do_work<CV_32F>},
{CV_16U, &do_work<CV_16U>}
};
用法是:
// my_cv_map gets implicitly converted to TensorBuilder<...>, allowing the worker to work with the proper tensor type.
workerMap[my_cv_map.type()](my_cv_map /*,...*/);
关于opencv - 确定数据类型并用作模板类型名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51609243/