我想将浮点数保存为图像中的像素。我目前正在使用opencv-python,但我也尝试使用Pillow(PIL)包。 两个包都将浮点像素数据转换为整数,然后将它们保存为图像。
我想保存:
npm find "kw1" "kw2"
但是当我打开保存的图像时,我得到:
(245.7865, 123.18788, 98.9866) in image.
不知何故,我的浮动数字会四舍五入并转换为整数。 如何阻止PIL或OpenCv将它们转换为整数??
答案 0 :(得分:0)
观察到的行为取决于保存图像的文件格式。很少有图像格式具有浮点像素值的规范。尽管有,但最重要的是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