Conversion of image type int16 to uint8
All of these do different things.
np.uint8
considers only the lowest byte of your number. It's like doing value & 0xff
.
>>> img = np.array([2000, -150, 11], dtype=np.int16)
>>> np.uint8(img)
array([208, 106, 11], dtype=uint8)
cv2.normalize
with the cv2.NORM_MINMAX
norm type normalises your values according to the normalisation function
img_new = (img - img.min()) * ((max_new - min_new) / (img.max() - img.min())) + min_new
It effectively changes one range to another and all the values in the between are scaled accordingly. By definition the original min/max values become the targetted min/max values.
>>> cv2.normalize(img, out, 0, 255, cv2.NORM_MINMAX)
array([255, 0, 19], dtype=int16)
uint8
in Matlab simply saturates your values. Everything above 255 becomes 255 and everything below 0 becomes 0.
>> uint8([2000 -150 11])
ans =
255 0 11
If you want to replicate Matlab's functionality, you can do
>>> img[img > 255] = 255
>>> img[img < 0] = 0
Which one you want to use depends on what you're trying to do. If your int16 covers the range of your pixel values and you want to rescale those to uint8, then cv2.normalize
is the answer.