Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
817 views
in Technique[技术] by (71.8m points)

opencv c++: converting image matrix from unsigned char to float

I have a problem with converting an image matrix. I use:

Mat image = imread(image_name, 0);

to read an image into the Mat object. When i look through the debugger, i see the data is stored as an unsigned char.

Next, i use convertTo method to convert the data to float values:

Mat image_f;
image.convertTo(image_f, CV_32F);

Again I look through the debugger and the data is still of type unsigned char.

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're checking the type wrong. Probably you look at image.data, which will always be uchar*, for any image type.

Try checking again, your types will be ok.

#include <opencv2opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main()
{
    Mat image(100, 100, CV_8UC1);
    cout << image.type() << " == " << CV_8U << endl;

    Mat image_f;
    image.convertTo(image_f, CV_32F);
    cout << image_f.type() << " == " << CV_32F << endl;

    return 0;
}

You can access float values like:

#include <opencv2opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main()
{
    Mat m(10,10,CV_32FC1);

    // you can access element at row "r" and col "c" like:
    int r = 2;
    int c = 3;

    // 1
    float f1 = m.at<float>(r,c);

    // 2
    float* fData1 = (float*)m.data;
    float f2 = fData1[r*m.step1() + c];

    // 3
    float* fData2 = m.ptr<float>(0);
    float f3 = fData2[r*m.step1() + c];

    // 4
    float* fData3 = m.ptr<float>(r);
    float f4 = fData3[c];

    // 5
    Mat1f mm(m); // Or directly create like: Mat1f mm(10,10);
    float f5 = mm(r,c);

    // f1 == f2 == f3 == f4 == f5


    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...