python - 转换为 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是错误的吗?如果我应该以什么格式输入我的服务?
解决方案
请注意,您不是简单地进行 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
。
推荐阅读
- regex - 如何在我的 Angular 6 正则表达式中忽略大小写?
- node.js - 将多个集合传递到同一条快速路线
- julia - 如何在 Julia 中加速多个广播
- qt - 在 QtCreator 中的小部件之后添加布局
- javascript - 如果选中复选框 javascript,则在 30 秒后重定向
- php - PHP - Scrape data of all trustpilot reviews
- css - 仅当元素位于屏幕的某个位置时如何触发动画?
- python - Python 3:使用循环在字符串中查找一组字母
- javascript - jquery将json数据返回为未定义并且图像未加载
- r - 获取因子(0)水平:在预测 NaiveBayes 模型中