我见过很多 OpenCV 代码,它们访问 a 的数据成员cv::Mat
直接地。cv::Mat
将指向数据的指针存储在unsigned char* data
成员。对数据成员的访问如下所示:
cv::Mat matUC(3,3,CV_8U)
int rowIdx = 1;
int colIdx = 1;
unsigned char val = matUC.data[ rowIdx * matUC.cols + colIdx]
我想知道这是否适用于cv::Mat
像素类型除unsigned char
.
cv::Mat matF(3,3,CV_32F)
int rowIdx = 1;
int colIdx = 1;
float val = matF.data[ rowIdx * matF.cols + colIdx];
我的理解是需要进行类型转换才能正确访问元素。就像是:
float val = ((float*)matF.data)[ rowIdx * matF.cols + colIdx];
我见过很多不使用类型转换的代码。所以我的问题是:类型转换是否必须访问正确的元素?
Mat
数据是一个uchar*
。如果你有一个浮点矩阵CV_32FC1
,您需要访问数据float
.
您可以通过不同的方式进行操作,不一定使用强制转换:
#include <opencv2\opencv.hpp>
using namespace cv;
int main()
{
cv::Mat matF(3, 3, CV_32F);
randu(matF, Scalar(0), Scalar(10));
int rowIdx = 1;
int colIdx = 1;
// 1
float f1 = matF.at<float>(rowIdx, colIdx);
// 2
float* fData2 = (float*)matF.data;
float f2 = fData2[rowIdx*matF.step1() + colIdx];
// 3
float* fData3 = matF.ptr<float>(0);
float f3 = fData3[rowIdx*matF.step1() + colIdx];
// 4
float* fData4 = matF.ptr<float>(rowIdx);
float f4 = fData4[colIdx];
// 5
Mat1f mm(matF); // Or directly create like: Mat1f mm(3, 3);
float f5 = mm(rowIdx, colIdx);
// f1 == f2 == f3 == f4 == f5
return 0;
}
Notes
- 最好用
step1()
代替cols
直接访问时data
通过指针,因为图像可能不连续。查看here更多细节。
- 该片段改编自此我的另一个答案
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)