Matlab – How does matlab function imwrite() scale the data while writing the output

fileioMATLAB

I am using matlab for some image processing. So in this context,
I have a question about the Matlab/Octave imwrite() function.

When I call imwrite as:

imwrite(img,'file.bmp');

where img is data of class/type double in Matlab and has negative values as well as positive values.

How does Matlab imwrite() function scale this data to write a BMP image which would have values between [0,255]. I could not understand the code of imwrite.m

What type of scaling/range adjustment does it do, Is it:-

1]

img = img - min(min(img));  

img = img .* ((255)/max(max(img)));

or any other type of scaling.

Thank you.

-AD.

Best Answer

It looks like you are writing the 2D matrix. This matrix will be written as indexed image. If no colormap provided, the image will be grayscale.

If the matrix img is of uint8 class, IMWRITE writes the actual values to the image file.

If the matrix is double, IMWRITE assumes all values are between 0 and 1. All negative values will be truncated to 0 and all larger than 1 values will be 1. Then they scaled by 255 and converted to uint8.

See Class Support in IMWRITE documentation.

EDIT

Here is how you can reproduce the conversion:

img = (rand(10)-0.5)*3;
imwrite(img,'test.bmp');
IMG = imread('test.bmp');

img2 = img;
img2(img2<0)=0;
img2(img2>1)=1;
img2 = uint8(img2*255);

%# compare imwrite vs. manual conversion
isequal(IMG,img2)

ans =

     1
Related Topic