opencv c ++:将图像矩阵从unsigned char转换为float

时间:2015-08-08 14:36:18

标签: c++ opencv

转换图像矩阵时遇到问题。我用:

Mat image = imread(image_name, 0);

将图像读入Mat对象。当我查看调试器时,我看到数据存储为unsigned char。

接下来,我使用convertTo方法将数据转换为浮点值:

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

我再次查看调试器,数据仍然是unsigned char类型。

我做错了什么?

1 个答案:

答案 0 :(得分:5)

您正在检查错误的类型。对于任何图像类型,您可能会看image.datauchar*始终为#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; }

再次尝试检查,您的类型就可以了。

float

您可以访问#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; } 之类的值:

echo yii\grid\GridView::widget([
  'dataProvider' => $dataProvider,
  'columns' => [
    'id',
    [
      'attribute' => 'Details',
      'format' => 'raw',
      'value' => function ($model) {
        return $this->render('//path/to/view.php', ['model' => $model]);
      },
    ]
  ]
]);