如何将一个numpy数组保存为webp文件?

huangapple go评论126阅读模式
英文:

How to save a numpy array to a webp file?

问题

我有一个numpy数组res

  1. res = \
  2. np.array([[[ 1, 142, 68],
  3. [ 1, 142, 74]],
  4. [[ 1, 142, 70],
  5. [ 1, 142, 77]],
  6. [[ 1, 142, 72],
  7. [ 1, 142, 79]],
  8. [[ 1, 142, 75],
  9. [ 1, 142, 82]]])

我想将其保存为webp文件,并检查是否可以恢复结果。

尝试一

  1. # 保存:
  2. Image.fromarray(res.astype(np.uint8), mode='RGB').save("test.webp", "WEBP")
  3. # 检查结果:
  4. np.array(Image.open("test.webp"))

输出结果为:

  1. array([[[ 2, 143, 75],
  2. [ 2, 143, 75]],
  3. [[ 2, 143, 75],
  4. [ 2, 143, 75]],
  5. [[ 2, 143, 75],
  6. [ 2, 143, 75]],
  7. [[ 2, 143, 75],
  8. [ 2, 143, 75]]], dtype=uint8)

尝试失败,因为这些数字与我在res中开始的数字不同。

尝试二

现在不使用.astype(np.uint8)

  1. # 保存:
  2. Image.fromarray(res, mode='RGB').save("test.webp", "WEBP")
  3. # 检查结果:
  4. np.array(Image.open("test.webp"))

输出结果为:

  1. array([[[ 2, 5, 31],
  2. [ 0, 0, 27]],
  3. [[17, 21, 40],
  4. [ 0, 0, 15]],
  5. [[ 0, 0, 3],
  6. [25, 32, 34]],
  7. [[ 0, 8, 1],
  8. [ 0, 7, 0]]], dtype=uint8)

这比尝试一还要糟糕。

我如何将numpy数组保存为webp文件?

英文:
  1. import numpy as np
  2. from PIL import Image

I have a numpy array res:

  1. res = \
  2. np.array([[[ 1, 142, 68],
  3. [ 1, 142, 74]],
  4. [[ 1, 142, 70],
  5. [ 1, 142, 77]],
  6. [[ 1, 142, 72],
  7. [ 1, 142, 79]],
  8. [[ 1, 142, 75],
  9. [ 1, 142, 82]]])

I would like to save it to a webp file and check if I can recover the result.

Attempt I

  1. # save:
  2. Image.fromarray(res.astype(np.uint8), mode='RGB').save("test.webp", "WEBP")
  3. # check result:
  4. np.array(Image.open("test.webp"))

This outputs:

  1. array([[[ 2, 143, 75],
  2. [ 2, 143, 75]],
  3. [[ 2, 143, 75],
  4. [ 2, 143, 75]],
  5. [[ 2, 143, 75],
  6. [ 2, 143, 75]],
  7. [[ 2, 143, 75],
  8. [ 2, 143, 75]]], dtype=uint8)

Attempt failed, as these aren't the same numbers as I started with in res.

Attempt II

Now without .astype(np.uint8):

  1. # save:
  2. Image.fromarray(res,mode='RGB').save("test.webp", "WEBP")
  3. # check result:
  4. np.array(Image.open("test.webp"))

This outputs:

  1. array([[[ 2, 5, 31],
  2. [ 0, 0, 27]],
  3. [[17, 21, 40],
  4. [ 0, 0, 15]],
  5. [[ 0, 0, 3],
  6. [25, 32, 34]],
  7. [[ 0, 8, 1],
  8. [ 0, 7, 0]]], dtype=uint8)

This is even worse than Attempt I.

How can I save a numpy array to a webp file?

答案1

得分: 2

尝试以无损方式保存WEBP文件,如果您想要完全相同的值,可以使用以下代码:

  1. im.save('im.webp', lossless=True)

关于每种文件格式可以处理的具体细节可以在这里找到。

英文:

Try saving your WEBP losslessly if you want the exact same values back, e.g. something like:

  1. im.save('im.webp', lossless=True)

The specifics of what each file format can handle are documented here.

huangapple
  • 本文由 发表于 2023年8月8日 20:21:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76859518.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定