首页 > 解决方案 > 如何在图像文件中保存浮点像素值

问题描述

我想将浮点数保存为图像文件中的像素。我目前正在使用 OpenCV-python,但我也尝试过使用 Pillow (PIL)。这两个包都将float像素数据转换为整数,然后再将它们写入文件。

我想保存像素值,例如:

(245.7865, 123.18788, 98.9866)

但是当我读回图像文件时,我得到:

(246, 123, 99)

不知何故,我的浮点数被四舍五入并转换为整数。如何阻止 PIL 或 OpenCV 将它们转换为整数?

标签: pythonimageopencvpython-imaging-library

解决方案


您观察到的行为取决于您保存图像的文件格式。很少有图像格式具有浮点像素值的规范。虽然有些人这样做,但首先是 TIFF。

要使用 TIFF 图像编写器演示所需的行为,请考虑以下脚本。它使用通用图像输入/输出库ImageIO,它依赖 PILlow 作为其后端之一:

# Use Stack Overflow logo as sample image.
import imageio
logo = 'https://cdn.sstatic.net/Sites/stackoverflow/img/logo.png'
image = imageio.imread(logo)

# Normalize to 1. Pixel values are now floating-point.
image = image / image.max()

# Save as image file and read back in.
format = 'tiff'
imageio.imwrite(f'image.{format}', image)
print(f'wrote: {image.dtype}')
image = imageio.imread(f'image.{format}')
print(f'read:  {image.dtype}')

该脚本的输出是:

wrote: float64
read:  float64

另一方面,如果将格式更改为 PNG(format = 'png'在代码中),则输出为:

Lossy conversion from float64 to uint8. Range [0, 1].
Convert image to uint8 prior to saving to suppress this warning.
wrote: float64
read:  uint8

推荐阅读