convert int16 to uint16 without losing information

36 visualizaciones (últimos 30 días)
Bob Read
Bob Read el 1 de Feb. de 2018
Comentada: Guillaume el 3 de Abr. de 2018
I have a range of int16 values from -32768 to 32767 and want to convert these to uint16 values from 0 to 65535. I can't get this to work. Negative values get truncated to zero.
  1 comentario
Adam
Adam el 1 de Feb. de 2018
Editada: Adam el 1 de Feb. de 2018
Can't you just cast to double, add 32768, then cast to uint16?

Iniciar sesión para comentar.

Respuestas (3)

Bob Read
Bob Read el 1 de Feb. de 2018
Thanks to the person who suggesting casting to double, that's solved my problem.
  2 comentarios
Adam
Adam el 1 de Feb. de 2018
If this is something you do more than once I'd recommend creating a function to do it though so you don't need to do the maths each time. There may be a function in Matlab that does this, but neither cast nor typecast do.
There are functions in the image processing toolbox that do some kind of more friendly casting though, I just can't remember what they are off-hand. They'd be no better than writing your own as above though.
Guillaume
Guillaume el 3 de Abr. de 2018
The image processing functions are im2xxx, in this case, im2uint16. They're implemented as mex files and hopefully only involve bit twiddling so should be faster than converting to double and back (which is going to be slow relatively speaking).

Iniciar sesión para comentar.


nicolas potier
nicolas potier el 30 de Mzo. de 2018
https://la.mathworks.com/help/matlab/ref/typecast.html?searchHighlight=typecast&s_tid=doc_srchtitle
Esta es la función que necesita. Espero le sirva - >> typecast ----->Guarda los datos y no los pierde
  2 comentarios
Adam
Adam el 3 de Abr. de 2018
typecast won't shift data to the new range, it will just wrap the data within the new data type e.g.
>> typecast( int16( -32768 ), 'uint16' )
ans =
uint16
32768
Guillaume
Guillaume el 3 de Abr. de 2018
At that point, you only need to toggle the MSB and you're done.

Iniciar sesión para comentar.


Guillaume
Guillaume el 3 de Abr. de 2018
It's an old thread but since it's been revived: In theory, the following should be faster than transitioning to double as it's just very simple bit toggling:
testarray = [intmin('int16'), -1, 0, 1, intmax('int16')]
asuint16 = bitxor(typecast(testarray, 'uint16'), uint16(32768))
In practice it may be the same speed, depending on how uint16 is implemented. If it read 32768 as double then convert to uint16, then it'll be slow (As conversions between floating point and integers are a lot more involved than just bit twiddling)

Categorías

Más información sobre Convert Image Type en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by