How to use cv :: Mat :: convertTo
I am writing a function that takes a cv :: Mat of an arbitrary type, converts it to a floating image, processes it, and converts it back to its original type. The problem is that not the easy ways I have come up with works. Here's what I've 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;
}
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 to do this? I am using OpenCV 2.4.10 for Windows.
source to share
The problem is with the pattern cv::Mat_<float>
. Apparently cv::Mat::convertTo()
it cannot accept Mat_<>
as output. Additionally cv::Mat_<float>::operator=()
works differently than cv::Mat:operator=()
. It will implicitly convert the image to the appropriate format.
It makes sense as soon as you think about it.
source to share