[英]How to use cv::Mat::convertTo
我正在編寫一個函數,它接受任意類型的 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。
問題是模板化的cv::Mat_<float>
。 顯然cv::Mat::convertTo()
不能將Mat_<>
作為輸出。 此外cv::Mat_<float>::operator=()
工作方式與cv::Mat:operator=()
。 它隱式地將圖像轉換為適當的格式。
一旦你想到它就有意義了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.