Search code examples
imagematlabcomputer-visionmatlab-cvststereo-3d

read disparity map using png file


I calculate a disparity map

d = disparity(imgL,imgR, 'Method', 'SemiGlobal', 'BlockSize', 7);

If I want to save the disparity map in image file

dis1 = d/63;  imwrite(dis1,'dis.png');

How to read this disparity map in Matlab?

I tried:

disparityMap= single(imread('dis.png')/63);

But it doesn't give the same matrix. Thanks


Solution

  • The problem with saving PNG files with imwrite is that for floating point images such as your disparity map, the function multiplies the data by 255 and truncates the data to 8-bit unsigned integer before saving. Therefore if you try to re-read this image, you will need to divide by 255 to get it back to what it was before but due to truncation you will definitely get precision loss. You can approximate what you had before by first dividing 255 to get your scaled disparity map, then you need to multiply by 63 to undo your previous division by 63... oh yeah, and by the way you need to convert the datatype first before doing the division or else you will be subject to truncation of the datatype and that's also where you're going wrong too:

    disparityMap = single(imread('dis.png'))*(63/255);
    

    Be wary that you will not get it exactly the same as you had it before due to the precision loss when dividing by 63 and also when writing to file. The division by 63 will make small disparities even smaller so that when you actually scale by 255, truncate and save to file, these small disparities will inevitably get mapped to a smaller number when you read the file back into memory. Therefore, you need to make absolutely sure that this is what you actually want to do.