You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将numpy数组保存为WebP文件并准确恢复原始数据?

解决Numpy数组保存为WebP后数据失真的问题

你之前的尝试失败核心原因是WebP默认采用有损压缩,会对像素数据做不可逆优化,导致原始数值无法保留。要精准还原原始数据,必须启用WebP的无损压缩模式。

正确实现代码

import numpy as np
from PIL import Image

# 原始数组
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
Image.fromarray(res.astype(np.uint8), mode='RGB').save("test.webp", "WEBP", lossless=True)

# 读取验证
recovered = np.array(Image.open("test.webp"))

# 检查数据一致性
print(np.array_equal(res, recovered))
# 输出:True

关键细节说明

  • 必须用astype(np.uint8):你的原始数组元素都在0-255范围内,符合uint8类型要求,PIL处理图像需要对应的数据类型,否则会出现解析错误(即你尝试二的异常结果)。
  • lossless=True是核心:开启后WebP采用无损压缩算法,保证像素数据完全还原,无数值损失。
  • 可选优化:如果需要调整无损压缩的效率,可添加method参数(取值0-6,数值越高压缩率越高但速度越慢),例如method=6。

内容的提问来源于stack exchange,提问作者zabop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 17:55:02