简体   繁体   中英

Get data from mat C openCV

I have some C++ openCV code.

Something like

void foo(...., Mat mx){
   ...
   x_d = mx.at<float>(x,y);
   ...
}

I try rewrite this part in C. I read docs and they say that data is union inside CvMap structure. But i got different error messages while try to get it. Here they are:

void foo(...., CvMat *mx){
   ...
   x_d = *(((float*)mx->data) + y * width + x); // cannot convert to a pointer type
   x_d = *(mx->data + y * width + x); // invalid operands to binary + (have 'union <anonymous>' and 'int')
   ...
}

So i have two questions. How I can get that float from structure this code? Is this the data that I need?

You can use Get?D functions, or CV_MAT_ELEM macro.

See the example below:

#include <opencv2\opencv.hpp>
using namespace cv;

int main()
{
    CvMat* m = cvCreateMat(2, 3, CV_32FC1);
    cvSet(m, cvScalar(1.0f));
    cvSet2D(m, 0, 1, cvScalar(2.0f));

    // m
    // 1.0 2.0 1.0 
    // 1.0 1.0 1.0 

    // Using cvGet2d

    CvScalar v00 = cvGet2D(m, 0, 0);
    float f00 = v00.val[0];
    // f00 = 1.0

    CvScalar v01 = cvGet2D(m, 0, 1);
    float f01 = v01.val[0];
    // f00 = 2.0

    // Using CV_MAT_ELEM

    float g00 = CV_MAT_ELEM(*m, float, 0, 0);
    // g00 = 1.0

    float g01 = CV_MAT_ELEM(*m, float, 0, 1);
    // g01 = 2.0


    return 0;
}

The first instruction seems to be almost correct but the error is saying that you try treat the result as pointer. Obviously it's not a pointer, but a number. Probably float. Try this:

x_d = (((float*)mx->data) + y * width + x);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM