首页 > 解决方案 > 转换为 base64 更改 numpy 数组

问题描述

我有一个服务,它接受输入一个 base64 图像,将其转换为 numpy 数组,对其执行一些操作,然后将其转换回 base64 图像,作为输出发送。但是 numpy 数组在转换为 base64 期间被修改。

我创建了一个示例来演示该问题。

import base64
from io import BytesIO
import numpy as np
from PIL import Image

img = np.array([[[1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3]]]
               ).astype(np.uint8)
print(img)
image_format = 'JPEG'

pil_img = Image.fromarray(img)
buff = BytesIO()
pil_img.save(buff, format=image_format)
encrypted_image = base64.b64encode(buff.getvalue()).decode('utf-8')

base64_decoded = base64.b64decode(encrypted_image)
img2 = Image.open(BytesIO(base64_decoded))
img2 = np.array(img2)

print(img2)

输出:

[[[1 2 3]
  [1 2 3]]

 [[1 2 3]
  [1 2 3]]]
[[[1 2 4]
  [1 2 4]]

 [[1 2 4]
  [1 2 4]]]

img2 的最后一列与 img 的最后一列不同,但我希望它是相同的。

转换为base64是错误的吗?如果我应该以什么格式输入我的服务?

标签: pythonnumpybase64python-imaging-library

解决方案


请注意,您不是简单地进行 base64 编码/解码。而不是x == base64.decode(base64.encode(x))你在做 base64.decode(base64.encode(jpeg.deflate(jpeg.compress(x)))) == x

base64 的部分是位精确的,但 JPEG 压缩的部分只会给出一个近似值。换句话说,不是 trujpeg.deflate(jpeg.compress(x))总是等于x


推荐阅读