首页 > 解决方案 > 将 numpy 图像数组从 -1、1 标准化到 0,255

问题描述

我有一个形状为 (32,32,32,3) 的 numpy 图像数组,为 (batchsize,height,width,channel)。

这些值介于 - 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))

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

标签: pythonnumpyimage-processingnormalize

解决方案


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

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()

推荐阅读