Question

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?

Was it helpful?

Solution

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))

OTHER TIPS

I think the values you write should be integers.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top