Why MATLABs "imwrite" scale 12-bit images and how to get around this?
I have an image presented as N x M
- matrix with 12 bit data and I want to use imwrite
to save the image as a file .pgm
.
Why does MATLAB scale the image to 16 bits? How can I get around this?
Using the argument 'MaxValue'
also seems to change the image as it cannot be displayed correctly afterwards, eg. in IrfanView.
source to share
The parameter is a MaxValue
bit intuitive. It indicates that the PGM entry is tagged with the maximum value of a certain depth (for example, 12 bits here), but also tells you to iwwrite
rescale the data. Re-scaling occurs in writepnm>remap_pixel_values
:
function newdata = remap_pixel_values(data, maxval)
%REMAP_PIXEL_VALUES Remap pixel values in array of pixel values.
%
% NEWDATA = REMAP_PIXEL_VALUES(DATA, MAXVAL) remaps the pixel values in
% DATA as follows
%
% Class of DATA Input Output
% ------------- ----- ------
% uint8 The set {0,1,...,255} The set {0,1,...,maxval}
% uint16 The set {0,1,...,65535} The set {0,1,...,maxval}
% double The interval [0,1] The set {0,1,...,maxval}
So with the data, uint16
it will scale the data by applying the scale 65535/maxval
through the bit shift bitshift(data,-4);
. You don't want it to rescan the data, but you also want it to write the file as 12-bit (this happens in writepnm>write_raw_data
. A workaround is to apply the opposite scale before calling imwrite
:
Iscaled = uint16(double(I)*(2^16-1)/(2^12-1))
imwrite(Iscaled,'test.pgm','MaxValue',2^12-1)
Note that you can use double values ββscaled between [0,1] according to the table in the code comments above.
For 12-bit PGM / PPM reading see here .
source to share