转换为 base64 会更改 numpy 数组

Converting to base64 changes numpy array

我有一项服务可以输入 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错了?如果我应该以什么格式为我的服务输入?

请注意,您不只是在做 base64 encoding/decoding。 而不是 x == base64.decode(base64.encode(x)) 你正在做 base64.decode(base64.encode(jpeg.deflate(jpeg.compress(x)))) == x

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

是不正确的