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. 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.
The problem is the templated cv::Mat_<float>
. Apparently cv::Mat::convertTo()
cannot take a Mat_<>
as an output. Additionally cv::Mat_<float>::operator=()
works differently than cv::Mat:operator=()
. It implicitly converts the image to the appropriate format.
It makes sense once you think of it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.