MATLAB Answers

Image conversion from uint16 to uint8 mismatch

72 views (last 30 days)
Hey all,
I am a little confused in converting images from uint16 to uint8. There is a matlab function im2uint8 that should do the job, but I would like to avoid using the toolbox and convert using uint8 command. The conversion is done as follows:
u16 = uint16([126 127 128 129 130]) % sample 16bit data
u8 = uint8(u16/256) % scale and convert to 8bits
u8_2 = im2uint8(u16) % compare to built in fcn
However, I get some discrepancies between the two conversions.
For uint16 value of 128, the im2uint8 function gives zero, while the uint8 command gives 1. To my understanding it should be 1, but since Matlab gives it as 0, it made me confused. What am I missing here?

Accepted Answer

Steve Eddins
Steve Eddins on 12 Jan 2021
im2uint8 is using a scale factor of (255/65535), not 1/256.
Note that scaling the maximum of the uint16 range, 65535, by 1/256 produces 255.9961 (approximately), which is greater than the maximum value in the uint8 range. That's why 1/256 is not used.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by