在OpenCV C ++中转换数据表示形式 [英] Converting data representation in OpenCV C++

查看:80
本文介绍了在OpenCV C ++中转换数据表示形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已加载图像(cv :: mat),所有像素似乎都存储为未签名的字符.我需要将它们转换为32位浮点类型,以便可以执行一些数学运算. 我尝试过:

I have loaded an image (cv::mat) and all the pixels seem to be stored as unsigned chars. I need to convert them to 32-bit floating point type so I can perform some math operations. I have tried:

Mat M;
M = imread("path\\to\\image", CV_LOAD_IMAGE_COLOR);   
cvtColor( M, M, CV_RGB2GRAY);       
M.convertTo(M,CV_32F); 

并像这样初始化:

Mat test = Mat(100,100,CV_32F);

但是他们似乎什么也没做,数据仍然表示为未签名的字符.如何转换cv :: mat数据表示形式?

but they don't seem to do anything, the data is still represented as unsigned chars. How do I convert the cv::mat data representation?

推荐答案

即使使用非uchar格式,图像数据也始终由unsigned char* Mat::data指向.转换没问题,需要记住的是,要访问您的float数据,您需要从data指针进行 cast .一些例子:

The image data will always be pointed by unsigned char* Mat::data, even when it has a non-uchar format. Your conversion is OK, what you need to keep in mind is that, to access your float data, you will need to cast from the data pointer. Some examples:

1)访问第i个数据行

float * row_i = M.ptr<float>(i);

2)访问(i,j)元素:

2) Access to the (i,j) element:

float x_ij = M.at<float>(i,j)

或(更有效):

float x_ij = (M.ptr<float>(i))[j]


顺便说一句,您应该使用BGR2GRAY代替cvtColor中的RGB2GRAY:


BTW, you should use BGR2GRAY instead of RGB2GRAY in cvtColor:

cvtColor( M, M, CV_BGR2GRAY);

这篇关于在OpenCV C ++中转换数据表示形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆