图像类型int16到uint8的转换
我有一个数据类型为int16
的图像.
因此,当我必须将其范围转换为0-255时,我有两种方法可以在Python中实现.
I have an image with data type int16
.
So when I have to convert its range to 0-255, I got two ways to do that in Python.
1)直接使用numpy.uint8
功能
2)在0-255范围内使用OpenCV cv2.normalize
函数,然后使用numpy.uint8
.
2) Use OpenCV cv2.normalize
function with 0-255 range and then use numpy.uint8
.
在Matlab中,我们直接使用uint8
函数进行转换.
在
In Matlab, we directly get the conversion using uint8
function.
In
在第二种情况下,我使用了NORM_MINMAX
,强度值的范围也更改为0-4
.
Also in second case, I used NORM_MINMAX
and the range of intensity values gets changed to 0-4
.
进行转换的正确方法是什么?
What is the correct way to do the conversion?
所有这些都做不同的事情.
All of these do different things.
np.uint8
仅考虑数字的最低字节.就像在做value & 0xff
.
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.NORM_MINMAX
的 cv2.normalize
根据规范化功能
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)
Matlab中的
uint8
只会使您的值饱和.高于255的所有内容变为255,低于0的所有内容变为0.
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
如果您想复制Matlab的功能,则可以
If you want to replicate Matlab's functionality, you can do
>>> img[img > 255] = 255
>>> img[img < 0] = 0
您要使用哪一个取决于您要执行的操作.如果int16覆盖了像素值的范围,并且您想将其缩放为uint8,那么答案就是cv2.normalize
.