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

问题描述 投票:0回答:1
import numpy as np
from PIL import Image

我有一个 numpy 数组

res

res = \
np.array([[[  1, 142,  68],
           [  1, 142,  74]],
   
          [[  1, 142,  70],
           [  1, 142,  77]],
   
          [[  1, 142,  72],
           [  1, 142,  79]],
   
          [[  1, 142,  75],
           [  1, 142,  82]]])

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

我尝试

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

输出:

array([[[  2, 143,  75],
        [  2, 143,  75]],

       [[  2, 143,  75],
        [  2, 143,  75]],

       [[  2, 143,  75],
        [  2, 143,  75]],

       [[  2, 143,  75],
        [  2, 143,  75]]], dtype=uint8)

尝试失败,因为这些数字与我在

res
中开始时的数字不同。

尝试二

现在没有

.astype(np.uint8)

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

输出:

array([[[ 2,  5, 31],
        [ 0,  0, 27]],

       [[17, 21, 40],
        [ 0,  0, 15]],

       [[ 0,  0,  3],
        [25, 32, 34]],

       [[ 0,  8,  1],
        [ 0,  7,  0]]], dtype=uint8)

这比尝试 I 还要糟糕。

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

python numpy python-imaging-library rgb webp
1个回答
1
投票

如果您想要返回完全相同的值,请尝试无损保存您的 WEBP,例如像这样的东西:

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

每种文件格式可以处理的具体信息记录在here

© www.soinside.com 2019 - 2024. All rights reserved.