python - 如何在图像文件中保存浮点像素值
问题描述
我想将浮点数保存为图像文件中的像素。我目前正在使用 OpenCV-python,但我也尝试过使用 Pillow (PIL)。这两个包都将float
像素数据转换为整数,然后再将它们写入文件。
我想保存像素值,例如:
(245.7865, 123.18788, 98.9866)
但是当我读回图像文件时,我得到:
(246, 123, 99)
不知何故,我的浮点数被四舍五入并转换为整数。如何阻止 PIL 或 OpenCV 将它们转换为整数?
解决方案
您观察到的行为取决于您保存图像的文件格式。很少有图像格式具有浮点像素值的规范。虽然有些人这样做,但首先是 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
推荐阅读
- angularjs - 隐藏基于Angularjs中的状态值
- javascript - 使用 getUserMedia 的 iOS 设备不会出现 1080p 分辨率
- vue.js - 当语言模式设置为 Vue 时,样式 Intellisense 在 VS Code 中不起作用
- python - 是否可以将 django-cryptography 与 filter 或 get 方法一起使用?
- html - 将最后一个孩子放在前一个孩子旁边 - Flexbox
- r - 从 ks 包绘制 kde.local.test 结果时,fhat 评估点的误差单调增加
- api - 通用 Windows 平台上的 User32 Windows UI Api
- java - 将谷歌地图添加到底部导航栏的按钮
- list - 检查连续元素之间的差异是否相同
- matlab - 为什么在 MATLAB 中允许使用多个连续的加号语法?