MATLAB: Does the grayscale image I have saved with IMWRITE appears as black and white in MATLAB 7.3 (R2006b)

imshowimwriteMATLAB

I have created an grayscale image:
A=repmat(-100:100,100,1);
figure(1)
imshow(A,[])
I save this image to a file using IMWRITE as a 16bit image and it becomes black and white:
imwrite(A,'myimage.png','BitDepth',16)
figure(2)
imshow('myimage.png')

Best Answer

The issue you are experiencing with the IMWRITE function not saving the image correctly has to do with the way IMWRITE interprets the data when its first argument is of class DOUBLE.
If the matrix of type DOUBLE is passed to the IMWRITE function, then IMWRITE maps the data to the colormap using a range from 0 to 1. All the values in the matrix of type DOUBLE that is passed to IMWRITE that are less than or equal to 0 are mapped to 0 and all the value that are greater than or equal to 1 are mapped to 1. Since in the original matrix A all the values are either 0,1, negative or greater than 1, all the data is mapped to 0 or 1 and you see only 2 colors. To save the image properly, before using IMWRITE, shift the data such that its minimum is zero and then scale your data such that the maximum value of the data is 1, as follows:
A=A-min(A(:)); % shift data such that the smallest element of A is 0
A=A/max(A(:)); % normalize the shifted data to 1
imwrite(A,'myimage.png', 'BitDepth', 16);
figure(3)
imshow('myimage.png')
For more information on the IMWRITE function please refer to the documentation by executing the following in the MATLAB command line:
doc imwrite
Related Question