【问题标题】:How to save floating-point pixel values in image file如何在图像文件中保存浮点像素值
【发布时间】:2018-10-23 03:57:22
【问题描述】:

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

我想保存像素值如:

(245.7865, 123.18788, 98.9866)

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

(246, 123, 99)

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

【问题讨论】:

  • 可能使用支持浮点数的图像格式,例如 TIFF 或 PFM...netpbm.sourceforge.net/doc/pfm.html
  • 或使用OpenCV::FileStorage。
  • Python Wand 可以保存到 TIFF 或 PFM。

标签: python image opencv python-imaging-library


【解决方案1】:

光栅图像通常仅存储为整数值。而是像这样保存numpy数组directly

x = numpy.array([1, 2, 3])
with open('x.npy', 'wb') as f:
    numpy.save(f, x)

然后像这样加载变量

x = numpy.load('x.npy')

其他选择包括

  • 保存一张或多张 GREY16 png 图像,其中浮点数相乘并被截断。
  • 使用支持浮点数的Netpbm 格式。
  • 保存pickle。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 这个解决方案很棒,但是,您知道为什么无法打开生成的文件吗?我终于设法保存和恢复文件,但我无法使用 Windows 附带的任何照片查看器打开它。任何想法将不胜感激!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    相关资源
    最近更新 更多