Change image type : Convert 8U to 32F or 64F

void Mat::convertTo(OutputArray m, int rtype, double alpha=1, double beta=0 )

  • m – output matrix; if it does not have a proper size or type before the operation, it is reallocated.
  • rtype – desired output matrix type or, rather, the depth since the number of channels are the same as the input has; if rtype is negative, the output matrix will have the same type as the input.
  • alpha – optional scale factor.
  • beta – optional delta added to the scaled values.
saturate_cast<> is applied at the end to avoid possible overflows:
m(x,y) = saturate \_ cast<rType>( \alpha (*this)(x,y) +  \beta )


  1. Load an image 
  2. Convert image type
  3. Show result



#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "iostream"

using namespace cv;
using namespace std;

int main( )

    Mat src1;
    src1 = imread("lena.jpg", CV_LOAD_IMAGE_COLOR); 
    namedWindow( "Original image", CV_WINDOW_AUTOSIZE ); 
    imshow( "Original image", src1 ); 
    Mat dst,dst1;
    // Change image type from 8UC1 to 32FC1
    src1.convertTo(dst, CV_32F);

    cout << "src1 intensity = " << (int)<Vec3b>(2,5)[0] << endl << "dst intensity = " <<<Vec3f>(2,5)[0] <<endl << endl;
    // both intensity are same, but one is 8U and other is 32F

    dst.convertTo(dst1,CV_8U,1.5,10); // converting back to 8U with scaling
    namedWindow( "dst1", CV_WINDOW_AUTOSIZE );  
    imshow( "dst1", dst1 );
    return 0;


  1. src1.convertTo(dst, CV_32F);
    namedWindow("dst", CV_WINDOW_AUTOSIZE);
    imshow("dst", dst); Why I get a white screen?

    1. Generally we use unsigned 8 bit format to represent image, which is compatible in most of the library functions. When the image is converted to 32 bit, the imshow function is not able to display it properly. Probably, all nonzero values are considered as 1 when the image is in 32bit and the image looks like a white screen.