OpenCV Mat数据成员访问 [英] OpenCV Mat data member access

查看:256
本文介绍了OpenCV Mat数据成员访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到很多OpenCV代码直接访问 cv :: Mat 的数据成员。 cv :: Mat 将指向数据的指针存储在 unsigned char * data 成员中。访问数据成员如下所示:

I've seen a lot of OpenCV code which accesses the data member of a cv::Mat directly. cv::Mat stores the pointer to the data in a unsigned char* data member. Access to the data member looks like:

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

I'm wondering if this works for a cv::Mat with pixel type other than unsigned char.

cv::Mat matF(3,3,CV_32F)
int rowIdx = 1;
int colIdx = 1;

float val = matF.data[ rowIdx * matF.cols + colIdx];

我的理解是需要使用类型转换来正确访问元素。类似于:

My understanding would be that a typecast is needed to access the elements correctly. Something like:

float val = ((float*)matF.data)[ rowIdx * matF.cols + colIdx];

我见过很多不使用类型转换的代码。所以我的问题是:类型转换是否必须访问正确的元素?

I've seen a lot of code which doesn't use a typecast. So my question is: Is the typecast mandatory to access the correct element?

推荐答案

Mat 数据是 uchar * 。如果你有一个浮动矩阵 CV_32FC1 ,你需要以 float 的方式访问数据。

Mat data is an uchar*. If you have a, say, float matrix CV_32FC1, you need to access data as float.

你可以用不同的方式做,不一定使用演员:

You can do in different ways, not necessarily using casting:

#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;
}

注释


  • 最好使用 step1()而不是 cols 通过指针直接访问数据时,因为图像可能不连续。有关详细信息,请查看此处

  • 该片段是根据此我的其他答案

  • it's better to use step1() instead of cols when accessing directly data through pointers, since the image may not be continuous. Check here for more details.
  • The snippet is adapted from this my other answer

这篇关于OpenCV Mat数据成员访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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