opencv c ++:将图像矩阵从无符号字符转换为浮点数 [英] opencv c++: converting image matrix from unsigned char to float
本文介绍了opencv c ++:将图像矩阵从无符号字符转换为浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在转换图像矩阵时遇到问题.我使用:
I have a problem with converting an image matrix. I use:
Mat image = imread(image_name, 0);
将图像读取到Mat对象中.通过调试器查看时,我看到数据存储为无符号字符.
to read an image into the Mat object. When i look through the debugger, i see the data is stored as an unsigned char.
接下来,我使用convertTo方法将数据转换为浮点值:
Next, i use convertTo method to convert the data to float values:
Mat image_f;
image.convertTo(image_f, CV_32F);
再次检查调试器,数据仍然是unsigned char类型.
Again I look through the debugger and the data is still of type unsigned char.
我在做什么错了?
推荐答案
您正在检查类型错误.对于任何图像类型,您可能都会查看image.data
,该值始终为uchar*
.
You're checking the type wrong. Probably you look at image.data
, which will always be uchar*
, for any image type.
再次尝试检查,您的类型就可以了.
Try checking again, your types will be ok.
#include <opencv2\opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
Mat image(100, 100, CV_8UC1);
cout << image.type() << " == " << CV_8U << endl;
Mat image_f;
image.convertTo(image_f, CV_32F);
cout << image_f.type() << " == " << CV_32F << endl;
return 0;
}
您可以访问float
值,例如:
#include <opencv2\opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
Mat m(10,10,CV_32FC1);
// you can access element at row "r" and col "c" like:
int r = 2;
int c = 3;
// 1
float f1 = m.at<float>(r,c);
// 2
float* fData1 = (float*)m.data;
float f2 = fData1[r*m.step1() + c];
// 3
float* fData2 = m.ptr<float>(0);
float f3 = fData2[r*m.step1() + c];
// 4
float* fData3 = m.ptr<float>(r);
float f4 = fData3[c];
// 5
Mat1f mm(m); // Or directly create like: Mat1f mm(10,10);
float f5 = mm(r,c);
// f1 == f2 == f3 == f4 == f5
return 0;
}
这篇关于opencv c ++:将图像矩阵从无符号字符转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文