简体   繁体   English

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

[英]Converting ndarray from float32 to uint8 messes the image up

Following this blog I am trying to apply heatmap to the original image. 这个博客之后,我尝试将热图应用于原始图像。

However I have a problem converting float32 to uint8. 但是我在将float32转换为uint8时遇到问题。 Before converting to uint8 if I save the image with: 在转换为uint8之前,如果我将图像保存为:

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

will output this image: 将输出此图像:

在此处输入图片说明

After the line heatmap = np.uint8(255 * heatmap) I save the image again and get the following output: 在一行heatmap = np.uint8(255 * heatmap)我再次保存图像并获得以下输出:

在此处输入图片说明

The shape of image in both cases is (600, 600) . 在两种情况下,图像的形状都是(600, 600) So how can I get 2nd image to be the same as 1st after using uint8? 那么在使用uint8之后,如何使第二张图像与第一张图像相同?

You have only negative values in heatmap . 您在heatmap只有负值。 Since uint8 can only hold numbers between 0 and 255 the line heatmap = np.uint8(255 * heatmap) will only work as intended if the original values of heatmap are lying between 0. and 1. . 由于uint8只能之间保持数0255的线heatmap = np.uint8(255 * heatmap)将只按预期如果原始值工作heatmap中位于之间0.1.

Solution: 解:
Rescale the array to the range of [0,255] before casting it to uint8 : 在将数组强制转换为uint8之前,将数组重新缩放为[0,255]的范围:

heatmap = np.uint8(np.interp(heatmap, (heatmap.min(), heatmap.max()), (0, 255)))

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

相关问题 将图像从 float32 转换为 uint8 时,掩码 object 消失 - Masked object disapear when converting image from float32 into uint8 如何将栅格 dtype 从 uint8 转换为 float32? - How to convert raster dtype from uint8 to float32? 我应该如何将 float32 图像转换为 uint8 图像? - How should I convert a float32 image to an uint8 image? Tensorflow将uint8张量视为float32张量 - Tensorflow viewing a uint8 tensor as a float32 tensor 为什么我必须将“uint8”转换为“float32” - Why do i have to convert "uint8" into "float32" Keras Model Output是float32而不是uint8 ......尽管数据标签是uint8 - Keras Model Output is float32 instead of uint8… despite data labels being uint8 TensorFlow TypeError:传递给参数输入的值的 DataType uint8 不在允许值列表中:float16、float32 - TensorFlow TypeError: Value passed to parameter input has DataType uint8 not in list of allowed values: float16, float32 将uint8数组转换为图像 - Converting uint8 array to image 从float32转换为float时如何保持精度? - How to retain precision when converting from float32 to float? 错误:TypeError:传递给参数“输入”的值的 DataType uint8 不在允许值列表中:float16、bfloat16、float32、float64、int32 - Error: TypeError: Value passed to parameter 'input' has DataType uint8 not in list of allowed values: float16, bfloat16, float32, float64, int32
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM