Search code examples
matlabdisparity-mapping

Convert Matlab disparity image from single precision to uint8


I need to save the disparity image to my disk. The data type of the disparity image is single precision and the disparity range is [0 128]. While using imwrite(disparityMap,file_name), the saved image appears to be binary.


Solution

  • When you use imwrite with floating point precision, matlab consider that your data is in the range [0 1]. So any value above 1 will be considered as 1. That is why you have a black and white image.

    From matlab doc :

    If A is a grayscale or RGB color image of data type double or single, then imwrite assumes the dynamic range is [0,1] and automatically scales the data by 255 before writing it to the file as 8-bit values.

    Then, you have two solution. I'm considering that 128 is the maximum in your data, and that you want a colormap that goes from black to white. I will

    First solution, normalize your data so that matlab do the right conversion:

    % Normalize your data between 0 and 1
    disparityMap = disparityMap/128;
    
    % write the image
    imwrite(disparityMap,file_name)
    

    Second solution, do the conversion yourself and write the image directly as uint8:

    % Normalize your data between 0 and 255 and convert to uint8
    disparityMapU8 = uint8(disparityMap*255/128);
    
    % write the image as uint8
    imwrite(disparityMapU8,file_name)