[英]How to use cv::Mat::convertTo
I'm writing a function which takes a cv::Mat of arbitrary type, converts it to a float image, processes it and converts it back to it's original type.我正在编写一个函数,它接受任意类型的 cv::Mat,将其转换为浮点图像,对其进行处理并将其转换回原始类型。 The problem is that non of the simple ways I've come up with works.问题是我想出的所有简单方法都不起作用。 Here's what I tried so far:这是我到目前为止尝试过的:
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 ...\OpenCV\modules\core\src\matrix.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;
}
The calling function:调用函数:
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;
}
So, what would be the standard way of doing this?那么,这样做的标准方法是什么? I'm using OpenCV 2.4.10 on Windows.我在 Windows 上使用 OpenCV 2.4.10。
The problem is the templated cv::Mat_<float>
.问题是模板化的cv::Mat_<float>
。 Apparently cv::Mat::convertTo()
cannot take a Mat_<>
as an output.显然cv::Mat::convertTo()
不能将Mat_<>
作为输出。 Additionally cv::Mat_<float>::operator=()
works differently than cv::Mat:operator=()
.此外cv::Mat_<float>::operator=()
工作方式与cv::Mat:operator=()
。 It implicitly converts the image to the appropriate format.它隐式地将图像转换为适当的格式。
It makes sense once you think of it.一旦你想到它就有意义了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.