inline cv::Mat_ convertImage()

in source/util/CvUtil.h [227:265]


inline cv::Mat_<T> convertImage(const cv::Mat& imageIn) {
  // Create a dummy mat that will hold type, depth and channels for a given T
  cv::Mat_<T> infoMat;

  // Convert to desired depth
  cv::Mat imageOut = convertTo(imageIn, infoMat.depth());

  // Special case: OpenCV doesn't have a bool type, so Mat_<bool> is CV_8U [0..255]
  // We need to force values to be in [0..1]
  if (std::is_same<T, bool>::value) {
    cv::threshold(imageOut, imageOut, 127, 1, cv::THRESH_BINARY);
  }

  // Convert to desired number of channels
  const int chI = imageIn.channels();
  const int chO = infoMat.channels();
  if (chI == chO) {
    return imageOut;
  }

  if (chI == 1 && chO == 3) {
    cv::cvtColor(imageOut, imageOut, cv::COLOR_GRAY2BGR);
  } else if (chI == 1 && chO == 4) {
    cv::cvtColor(imageOut, imageOut, cv::COLOR_GRAY2BGRA);
  } else if (chI == 3 && chO == 1) {
    cv::cvtColor(imageOut, imageOut, cv::COLOR_BGR2GRAY);
  } else if (chI == 3 && chO == 4) {
    cv::cvtColor(imageOut, imageOut, cv::COLOR_BGR2BGRA);
  } else if (chI == 4 && chO == 1) {
    cv::cvtColor(imageOut, imageOut, cv::COLOR_BGRA2GRAY);
  } else if (chI == 4 && chO == 3) {
    cv::cvtColor(imageOut, imageOut, cv::COLOR_BGRA2BGR);
  } else {
    CHECK(false) << "Conversion from " << chI << " channels to " << chO
                 << " channels not supported";
  }

  return imageOut;
}