将ndarray从float32转换为uint8会使图像混乱

时间:2019-03-18 09:25:47

标签: python numpy

this blog之后,我尝试将热图应用于原始图像。

但是我在将float32转换为uint8时遇到问题。在转换为uint8之前,如果我将图像保存为:

plt.imshow(heatmap)
plt.savefig(f'{directory}/heatmap.png', bbox_inches='tight', pad_inches=0.0)

将输出此图像:

enter image description here

heatmap = np.uint8(255 * heatmap)行之后,我再次保存图像并获得以下输出:

enter image description here

两种情况下图像的形状均为(600, 600)。那么在使用uint8之后,如何使第二张图像与第一张图像相同?

1 个答案:

答案 0 :(得分:1)

heatmap中只有负值。由于uint8仅可容纳0255之间的数字,因此,如果heatmap = np.uint8(255 * heatmap)的原始值位于{{1 }}和heatmap

解决方案:
在将数组强制转换为0.之前,将数组重新缩放到1.的范围:

[0,255]