.jeg, .png, etc. formats would not work in your case since they are ment to keep uchar values. Instead you might be able to use .bmp
Try to use the following and see the result imwrite("~/imgout.bmp", cv::Mat(512, 512, CV_32FC1, gray)); if that does not work then saving the Mat by using the OpenEXR format might do the trick. So, you will need to save your Mat with an .exr extension but be careful because you need Opencv with that support to be compiled in. Thus something like that: imwrite("~/imgout.exr", cv::Mat(512, 512, CV_32FC1, gray));