归一化像素后如何保存图像?

How to save images after normalizing the pixels?

我想标准化我的图像并在训练中使用它。但是我在下面进行更改后找不到保存图像的方法。如何保存和加载它们?

files = ["/content/drive/MyDrive/Colab Notebooks/images/evre1/xyz.png",
         "/content/drive/MyDrive/Colab Notebooks/images/evre1/xty.png"]

def normalize(files):
  for i in files:

      image = Image.open(i)
      new_image =image.resize((224,224))
      pixels = asarray(image)
      # convert from integers to floats
      pixels = pixels.astype('float32')
      # calculate global mean and standard deviation
      mean, std = pixels.mean(), pixels.std()
      # print('Mean: %.3f, Standard Deviation: %.3f' % (mean, std))
      # global standardization of pixels
      pixels = (pixels - mean) / std
      # confirm it had the desired effect
      print(pixels)
      # mean, std = pixels.mean(), pixels.std()
      # print('Mean: %.3f, Standard Deviation: %.3f' % (mean, std))
  

normalize(files)

我尝试将它们保存为数组:

np.save(outfile, pixels)

然后,

_ = outfile.seek(0) 
t = np.load(outfile)

img_w, img_h = 224, 224
img = Image.fromarray(t, 'RGB')
img.save('test.png')
img.show()

但是没有图像出现..

我搜索了很多文档并花了很多时间来解决它...我正在等待任何帮助。谢谢。

我认为您最好的选择是将 meanstd 与每个标准化图像一起保存(在同一个 .npy 文件中)。

加载规范化图像时,还加载均值和标准差 - 这使我们能够恢复原始图像(在规范化之前)。


注:
我们可能会像这样显示规范化图像(例如):

Image.fromarray(((t-t.min())/(t.max()-t.min())*255).astype(np.uint8), 'RGB').show()

顺便问一下,恢复原始图像似乎是一个更好的解决方案。


使用原始均值和标准差保存和恢复归一化图像:

使用 meanstd 保存 pixels 的示例:

with open(outfile_name, 'wb') as f:
    np.save(f, pixels)  # Save the normalized image.
    np.save(f, np.array([mean, std]))  # Save mean and std as 2 elements numpy array after the "pixels" array (in the same file).

使用均值和标准差加载归一化图像,并还原并显示原始图像的示例:

with open(outfile_name, 'rb') as f:
    norm_t = np.load(f)  # Load normalized array
    mean_std = np.load(f)  # Load mean and std (that were saved before).
    mean, std = tuple(mean_std)  # Get mean and std as two scalars

    t = norm_t*std + mean  # Unnormalized (get the original pixels before normalizing)
    t = np.round(t.clip(0, 255)).astype(np.uint8)  # Convert from float to uint8 (use rounding and clipping for "cleaner" conversion).
    img = Image.fromarray(t, 'RGB')
    img.save('test.png')
    img.show()

完整代码示例(包括循环):

import numpy as np
from PIL import Image

files = ["xyz.png", "xty.png"]

def normalize(files):
    for i in files:
        image = Image.open(i)
        new_image = image.resize((224, 224))
        pixels = np.asarray(image)
        # convert from integers to floats
        pixels = pixels.astype('float32')
        # calculate global mean and standard deviation
        mean, std = pixels.mean(), pixels.std()
        # print('Mean: %.3f, Standard Deviation: %.3f' % (mean, std))
        # global standardization of pixels
        pixels = (pixels - mean) / std
        # confirm it had the desired effect
        print(pixels)
        # mean, std = pixels.mean(), pixels.std()
        # print('Mean: %.3f, Standard Deviation: %.3f' % (mean, std))

        #t = pixels
        #Image.fromarray(((t-t.min())/(t.max()-t.min())*255).astype(np.uint8), 'RGB').show()

        outfile_name = i.replace(".png", ".npy")  # "xyz.npy" and "xty.npy"

        # Save pixels, and also save np.array([mean, std]):
        with open(outfile_name, 'wb') as f:
            np.save(f, pixels)  # Save the normalized image.
            np.save(f, np.array([mean, std]))  # Save mean and std as 2 elements numpy array after the "pixels" array (in the same file).

        # Load outfile_name (normalized image) and [mean, std] array
        with open(outfile_name, 'rb') as f:
            norm_t = np.load(f)  # Load normalized array
            mean_std = np.load(f)  # Load mean and std (that were saved before).
            mean, std = tuple(mean_std)  # Get mean and std as two scalars

            t = norm_t*std + mean  # Unnormalized (get the original pixels before normalizing)
            t = np.round(t.clip(0, 255)).astype(np.uint8)  # Convert from float to uint8 (use rounding and clipping for "cleaner" conversion).
            img = Image.fromarray(t, 'RGB')
            img.save('test.png')
            img.show()
  
normalize(files)

如果要存储具有浮点像素的RGB图像,则不能使用PNG、JPEG、TGA或GIF格式。您或多或少不得不使用 TIFF 或 PFM - 尽管还有更晦涩的 HDR/EXR 格式可用。

您也不能将它们与 PIL/Pillow 一起使用,因为它不支持 32 位浮点 RGB 文件。

所以,简而言之,恕我直言,如果你想要浮动和 RGB,你可能想要:

  • TIFF(可能通过 tifffile)或 PFM(可能是 EXR)作为存储格式,并且
  • OpenCVscikit-imagelibvips 用于处理