简体   繁体   English

图像类型 int16 到 uint8 的转换

[英]Conversion of image type int16 to uint8

I have an image with data type int16 .我有一个数据类型为int16的图像。 So when I have to convert its range to 0-255, I got two ways to do that in Python.所以当我必须将它的范围转换为 0-255 时,我有两种方法可以在 Python 中做到这一点。

1) Use numpy.uint8 function directly 1)直接使用numpy.uint8函数

2) Use OpenCV cv2.normalize function with 0-255 range and then use numpy.uint8 . 2)使用0-255范围的OpenCV cv2.normalize函数,然后使用numpy.uint8

In Matlab, we directly get the conversion using uint8 function.在 Matlab 中,我们直接使用uint8函数进行转换。 In

Also in second case, I used NORM_MINMAX and the range of intensity values gets changed to 0-4 .同样在第二种情况下,我使用了NORM_MINMAX并且强度值的范围更改为0-4

What is the correct way to do the conversion?进行转换的正确方法是什么?

All of these do different things.所有这些都做不同的事情。

np.uint8 considers only the lowest byte of your number. np.uint8只考虑数字的最低字节。 It's like doing value & 0xff .这就像做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 cv2.normalizecv2.NORM_MINMAX范数类型根据 归一化函数归一化你的值

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. Matlab 中的uint8只是使您的值饱和。 Everything above 255 becomes 255 and everything below 0 becomes 0.高于 255 的所有内容都变为 255,低于 0 的所有内容都变为 0。

>> uint8([2000 -150 11])

ans =

  255    0   11

If you want to replicate Matlab's functionality, you can do如果你想复制 Matlab 的功能,你可以这样做

>>> 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.如果您的 int16 覆盖了像素值的范围,并且您想将它们重新缩放为 uint8,那么cv2.normalize就是答案。

the simply way to convert data format is to use the following formula.转换数据格式的简单方法是使用以下公式。 In this case it is possible to convert any array to a new custom format.在这种情况下,可以将任何数组转换为新的自定义格式。

# In the case of image, or matrix/array conversion to the uint8 [0, 255] 
# range

Import numpy as np

new_data = (newd_ata - np.min(new_data)) * ((255 - 0) / (np.max(new_data) - 
np.new_data))) + 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM