39
votes

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.

2
In Python, since the images are NumPy arrays, you can use img = img.astype(np.float32). - Burak

2 Answers

65
votes

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.

10
votes

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)