OpenCV C ++:如何通过uchar数据指针访问像素值CV_32F [英] OpenCV C++: how access pixel value CV_32F through uchar data pointer
本文介绍了OpenCV C ++:如何通过uchar数据指针访问像素值CV_32F的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
简而言之,我想知道是否可以直接访问像素值 通过Mat成员"uchar * data"对CV_32F Mat进行建模.
Briefly, I would like to know if it is possible to directly access pixel value of a CV_32F Mat, through Mat member "uchar* data".
如果Mat是CV_8U,我可以做到这一点,例如:
I can do it with no problem if Mat is CV_8U, for example:
// a matrix 5 columns and 6 rows, values in [0,255], all elements initialised at 12
cv:Mat A;
A.create(5,6, CV_8UC1);
A = cv::Scalar(12);
//here I successfully access to pixel [4,5]
uchar *p = A.data;
int value = (uchar) p[4*A.step + 5];
问题是,当我尝试使用以下矩阵进行相同的操作时,
The problem is when I try to do the same operation with the following matrix,
// a matrix 5 columns, 6 rows, values in [0.0, 1.0], all elements initialised at 1.2
cv::Mat B;
B.create(5,6, CV_32FC1);
B = cv::Scalar(1.2);
//this clearly does not work, no syntax error but erroneous value reported!
uchar *p = B.data;
float value = (float) p[4*B.step + 5];
//this works, but it is not what I want to do!
float value = B.at<float>(4,5);
非常感谢,Valerio
Thanks a lot, Valerio
推荐答案
您可以使用ptr
方法,该方法返回指向矩阵行的指针:
You can use ptr
method which returns pointer to matrix row:
for (int y = 0; y < mat.rows; ++y)
{
float* row_ptr = mat.ptr<float>(y);
for (int x = 0; x < mat.cols; ++x)
{
float val = row_ptr[x];
}
}
如果矩阵是连续的,还可以将data
指针强制转换为float并使用elem_step
而不是step
You can also cast data
pointer to float and use elem_step
instead of step
if matrix is continous:
float* ptr = (float*) mat.data;
size_t elem_step = mat.step / sizeof(float);
float val = ptr[i * elem_step + j];
这篇关于OpenCV C ++:如何通过uchar数据指针访问像素值CV_32F的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文