39

In OpenCV, if I have a Mat img that contains uchar data, how do I convert the data into float? Is there a function available? Thank you.

1
  • In Python, since the images are NumPy arrays, you can use img = img.astype(np.float32).
    – Burak
    Commented Jun 15, 2021 at 10:58

2 Answers 2

67

If you meant c++ then you have

#include<opencv2/opencv.hpp>
using namespace cv;
Mat img;
img.create(2,2,CV_8UC1);
Mat img2;
img.convertTo(img2, CV_32FC1); // or CV_32F works (too)

details in opencv2refman.pdf.

UPDATE:

CV_32FC1 is for 1-channel (C1, i.e. grey image) float valued (32F) pixels

CV_8UC1 is for 1-channel (C1, i.e. grey image) unsigned char (8UC) valued ones.

UPDATE 2:
According to Arthur Tacca, only CV_32F is correct (or presumably CV_8U), since convertTo should not change the number of channels. It sounds logical right? Nevertheless, when I have checked opencv reference manual, I could not find any info about this, but I agree with him.

7
  • Can you please tell me where we need to use 32F and 8U
    – AHF
    Commented Mar 31, 2014 at 11:45
  • this is actually my question , why where we need to use float valued pixel and where we need to use char valued ones
    – AHF
    Commented Mar 31, 2014 at 12:56
  • It depends on the bitdepth. If your grayscale image has the depth of 256 different colors, then it is 8UC1. The typical cases are 32FC1 for grayscale and 8UC3 for color. Commented Apr 3, 2014 at 8:15
  • @BarnabasSzabolcs Does this work with multi-channel images as well (i.e. convert CV_8UC3 to CV_8FC3)? Commented Feb 21, 2016 at 16:14
  • I'm not sure, you can try it with small images using matrix constructors to confirm that it works. docs.opencv.org/2.4/doc/tutorials/core/… Commented Feb 23, 2016 at 23:03
10

Use cvConvert function. In Python:

import cv
m = cv.CreateMat(2, 2, cv.CV_8UC1)
m1 = cv.CreateMat(2, 2, cv.CV_32FC1)
cv.Convert(m, m1)

Not the answer you're looking for? Browse other questions tagged or ask your own question.