c++ - 针对 C++ 类型测试 opencv mat 数据类型的最佳方法是什么?

标签 c++ templates opencv

我现在正在尝试自己在opencv lib中实现一些功能,例如将rgb图像转换为灰度。

为了使函数尽可能通用,我想让它能够处理 open cv (CV_8U, CV_8S, ... CV64F) 中的所有数据类型,即输出图像数据类型应与输入匹配图像数据类型。这涉及定义一些将保存类型作为输入图像数据类型的指针。

我知道无法在运行时确定输入的数据类型并初始化相应的指针,因此我必须在代码中使用某种开关来确定它。

在代码中,我有一个模板函数 t_convert_RGB_to_Gray<T>(...)定义为做实际工作。然后我有一个多功能 convert_RGB_to_Gray(...)能够确定数据类型并调用正确的转换函数。

我目前有以下两种数据类型测试方法:

方法一

     switch(image.depth())
    {
        case CV_8U: gray = t_convert_RGB_to_Gray<unsigned char>(image, coeff_R, coeff_G, coeff_B); break;
        case CV_8S: gray = t_convert_RGB_to_Gray<char>(image, coeff_R, coeff_G, coeff_B); break;
        case CV_16U:gray = t_convert_RGB_to_Gray<uint16_t>(image, coeff_R, coeff_G, coeff_B); break;
        case CV_16S:gray = t_convert_RGB_to_Gray<int16_t>(image, coeff_R, coeff_G, coeff_B); break;
        case CV_32S:gray = t_convert_RGB_to_Gray<int32_t>(image, coeff_R, coeff_G, coeff_B); break;
        case CV_32F:gray = t_convert_RGB_to_Gray<float>(image, coeff_R, coeff_G, coeff_B); break;
        case CV_64F:gray = t_convert_RGB_to_Gray<double>(image, coeff_R, coeff_G, coeff_B); break;
        default:    gray = t_convert_RGB_to_Gray<unsigned char>(image, coeff_R, coeff_G, coeff_B); break;
    }

方法二

if (cv::DataType<unsigned char>::depth == image.depth())
{
    // variation 1.
    //gray = t_convert_RGB_to_Gray<unsigned char>(image, coeff_R, coeff_G, coeff_B);
    // variation 2.
    gray = t_convert_RGB_to_Gray<cv::DataType<unsigned char>::channel_type>(image, coeff_R, coeff_G, coeff_B);
}
else if
 ....
}

我的问题是,这样做有什么缺点吗?有没有更好的方法呢?

谢谢!

最佳答案

要完成 Miki 的回答,您可以执行与第一种方法类似的操作:

switch(image.depth()) {
  case DataType<unsigned char>::type:
    gray = t_convert_RGB_to_Gray<unsigned char>(image, coeff_R, coeff_G, coeff_B);
    break;
  case DataType<int>::type:
    ...
}

关于c++ - 针对 C++ 类型测试 opencv mat 数据类型的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32402425/

相关文章:

c++ - FFmpeg 中 RGB 到 YUV 的转换错误

c++ - 将多个值插入 vector

php - 用于管理显示哪些内容的模板系统?

python - OpenCv代码抛出分割错误(核心转储)Ubuntu 14.04

opencv - 在 Ubuntu 14.04(64 位)中安装 FFmpeg

c++ - .get 函数在 C++ 中打开文件流

c++ - Eclipse C++ 内容辅助,自动激活

c++ - 广义复制构造函数

c++ - 无论如何我可以让一个模板<typename T>接受多个值吗?

python - 羽化裁剪边缘