我正在编写一个函数,它接受任意类型的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 ...\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;
}
调用函数:
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。
tmp;
而不是result = tmp
吗?tmp
已经具有正确的类型和表示。 - Alan Stokesstd::cout << a1.type() << " and " << b1.type() << std::endl
并告诉我们吗? - Mickacv::Mat b = cv::Mat::zeros(256, 256, 16UC1);
吗? - Mickacv::Mat result(input.size(), CV_32FC1);
,一切都能正常工作,至少对我来说是这样的...不确定这是否是一个错误或者.convertTo
不能从模板Mats中工作。 - Micka