Python 将ndarray从float32转换为uint8会弄乱图像
下面我尝试将热图应用于原始图像 但是,我在将float32转换为uint8时遇到问题。在转换为uint8之前,如果使用以下命令保存图像:Python 将ndarray从float32转换为uint8会弄乱图像,python,numpy,Python,Numpy,下面我尝试将热图应用于原始图像 但是,我在将float32转换为uint8时遇到问题。在转换为uint8之前,如果使用以下命令保存图像: plt.imshow(heatmap) plt.savefig(f'{directory}/heatmap.png', bbox_inches='tight', pad_inches=0.0) 将输出此图像: 在第heatmap=np.uint8(255*heatmap)行之后,我再次保存图像并获得以下输出: 两种情况下的图像形状都是(600600)。那
plt.imshow(heatmap)
plt.savefig(f'{directory}/heatmap.png', bbox_inches='tight', pad_inches=0.0)
将输出此图像:
在第heatmap=np.uint8(255*heatmap)
行之后,我再次保存图像并获得以下输出:
两种情况下的图像形状都是
(600600)
。那么,在使用uint8后,如何使第二张图像与第一张图像相同?热图中只有负值。由于uint8
只能容纳介于0
和255
之间的数字,因此行heatmap=np。uint8(255*heatmap)
只有在heatmap
的原始值介于0.
和1.
之间时才会按预期工作
解决方案:在将数组强制转换为
uint8
之前,将数组重新缩放到[0255]
的范围:
heatmap = np.uint8(np.interp(heatmap, (heatmap.min(), heatmap.max()), (0, 255)))
当我尝试时,一切都很好。你能发布你使用的完整代码吗?有趣的是,在你的评论之后,我在np.random.rand(32,32)上试过了,它工作正常。然而,我将ndarray转储到.npy文件中,在那里我得到了相同的结果。链接:“