2

I have a set of values between 0 and 1. After i put these values between 0 and 255 I want to save them as a grayscale image in pgm format. The problem is the fact that after I save it as an image the values i get when i read the image are different from the previous matrix with values between 0 and 255.

Here is an simple example:

>> a=[0.5,1,0.3]           

a =

0.5000    1.0000    0.3000


>> b=single(floor(255 * a))

%these are the values I want in the image
b =

127   255    76

imwrite(b, 'test.pgm'); 

% i don't want these values!!!
c=imread('test.pgm')    

c =

255  255  255

what's happening? why matlab does not save my values? is this a conversion issue?

mad
  • 2,677
  • 8
  • 35
  • 78

2 Answers2

2

what's happening? why matlab does not save my values? is this a conversion issue?

Yes, it's conversion issue and is not needed. MatLab automatically does conversion for you.

Hence, try storing a instead of b

imwrite(a, 'test.pgm'); 

Quoting from documentation of imwrite

imwrite(A,filename)

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


EDIT

If you want to stick to manual conversion, you need to type cast as uint8

b = uint8(floor(255 * a))
jkshah
  • 11,387
  • 6
  • 35
  • 45
  • Thank you for this information. I knew it, but when I save the values scaled in [0,255] in a file by multiplying the values by 255 and compare it to the matlab scaling, there are some few differences in the values. This happens because I use floor() to save the values and Matlab uses ceil(). Thank you too! – mad Nov 02 '13 at 17:29
1

I think the values you write should be integers.

Try b = uint16(floor(255 * a))

3lectrologos
  • 9,469
  • 4
  • 39
  • 46