如何使用cv :: mat :: convertto

How to use cv::Mat::convertTo

本文关键字:mat convertto cv 何使用      更新时间:2023-10-16

我正在编写一个函数,该函数采用了一个任意类型的cv :: mat,将其转换为浮动图像,对其进行处理并将其转换回原始类型。问题在于我想出的简单方式。这是我到目前为止尝试的:

cv::Mat process(const cv::Mat& input)// input might be float
{
    cv::Mat_<float> result(input.size());
   // Generate result based on input.
    result = ...;
    // Now convert result back to the type of input:
#if 1
    // Version 1: Converting in place crashes with:
    // OpenCV Error: Assertion failed (!fixedType() || ((Mat*)obj)->type() == mtype) in cv::_OutputArray::create,
    // file ...OpenCVmodulescoresrcmatrix.cpp, line 1365
    if (result.type() != input.type())
        result.convertTo(result, input.type());
#else
    // Version 2: Not what you'd expect
    if (result.type() != input.type())
    {
        cv::Mat tmp;
        result.convertTo(tmp, input.type());
        result = tmp;// This line doesn't replace result, but converts tmp back to float.
    }
#endif
    return result;
}

调用功能:

int main(int argc, char* argv[])
{
    cv::Mat_<float> a =  cv::Mat_<float>::zeros(256, 256);
    cv::Mat a1 = process(a);
    cv::Mat_<uint16_t> b =  cv::Mat_<uint16_t>::zeros(256, 256);
    cv::Mat b1 = process(b);
    assert(b1.type()==CV_16UC1);
    return 0;
}

那么,这样做的标准方式是什么?我正在Windows上使用OpenCV 2.4.10。

问题是模板的cv::Mat_<float>。显然,cv::Mat::convertTo()不能将Mat_<>作为输出。此外,cv::Mat_<float>::operator=()的工作方式与cv::Mat:operator=()不同。它隐含将图像转换为适当的格式。

一旦您想到它,那就有意义了。