【问题标题】:Normalising numpy array of images from -1, 1 to 0,255将 numpy 图像数组从 -1、1 标准化到 0,255
【发布时间】:2019-08-09 07:33:56
【问题描述】:

我有一个形状为 (32,32,32,3) 的 numpy 图像数组, 是(批量大小、高度、宽度、通道)。

值介于 - 1 和 1 之间,我希望将它们标准化/转换为整个数组的 0,255。

我尝试了以下解决方案:

realpics  = ((batch_images - batch_images.min()) * (1/(batch_images.max() - batch_images.min()) * 255).astype('uint8'))


realpics = np.interp(realpics, (realpics.min(), realpics.max()), (0, 255))

对此的任何帮助将不胜感激。

【问题讨论】:

  • 您目前遇到什么错误?
  • 没有错误,图像只是显示为白框。当在 -1 到 1 范围内时,它们显示正确

标签: python numpy image-processing normalize


【解决方案1】:

这里唯一棘手的部分是,当您从浮点数组转换回整数数组时,您必须注意浮点数如何映射到整数。对于您的情况,您需要确保所有浮点数都舍入到最接近的整数,那么您应该没问题。这是一个使用您的第一种方法的工作示例:

import numpy as np

raw_images = np.random.randint(0, 256, (32, 32, 32, 3), dtype=np.uint8)
batch_images = raw_images / 255 * 2 - 1 # normalize to [-1, 1]
recovered = (batch_images - batch_images.min()) * 255 / (batch_images.max() - batch_images.min())
recovered = np.rint(recovered).astype(np.uint8) # round before casting
assert (recovered == raw_images).all()

【讨论】:

  • 感谢您的回复。我尝试了您的解决方案,输出不再是白色而是静态的。这是i.imgur.com/CT2KgWp.png的输出,中间是-1到1的输出,左右是0到255的代码。
  • 您是否以与我在这里不同的方式将图像标准化为 [-1, 1]?如果您在原始图像上使用此规范化方法(即,将上面的 raw_images = ... 行替换为您获取图像的方式),断言不会通过吗?
猜你喜欢
  • 2020-12-25
  • 2016-08-19
  • 2013-01-04
  • 1970-01-01
  • 2018-10-18
  • 2017-03-14
  • 2011-06-22
  • 1970-01-01
  • 2020-03-19
相关资源
最近更新 更多