convert int16 to uint16 without losing information

조회 수: 31 (최근 30일)
Bob Read
Bob Read 2018년 2월 1일
댓글: Guillaume 2018년 4월 3일
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
Adam
Adam 2018년 2월 1일
편집: Adam 2018년 2월 1일
Can't you just cast to double, add 32768, then cast to uint16?

댓글을 달려면 로그인하십시오.

답변 (3개)

Bob Read
Bob Read 2018년 2월 1일
Thanks to the person who suggesting casting to double, that's solved my problem.
  댓글 수: 2
Adam
Adam 2018년 2월 1일
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 2018년 4월 3일
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).

댓글을 달려면 로그인하십시오.


nicolas potier
nicolas potier 2018년 3월 30일
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
Adam
Adam 2018년 4월 3일
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 2018년 4월 3일
At that point, you only need to toggle the MSB and you're done.

댓글을 달려면 로그인하십시오.


Guillaume
Guillaume 2018년 4월 3일
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)

카테고리

Help CenterFile Exchange에서 Convert Image Type에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by