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

前端 未结 1 1908
隐瞒了意图╮
隐瞒了意图╮ 2020-12-06 22:53

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 lo

相关标签:
1条回答
  • 2020-12-06 23:37

    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 <opencv2\opencv.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 <opencv2\opencv.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;
    }
    
    0 讨论(0)
提交回复
热议问题