0

我有一个 3 维 numpy 数组中的 RGB 图像。

我目前正在使用这个

base64.b64encode(img).decode('utf-8')

但是当我将输出复制/粘贴到这个网站https://codebeautify.org/base64-to-image-converter

它不会将图像转换回来。

但如果我使用这段代码:

import base64
with open("my_image.jpg", "rb") as img_file:
    my_string = base64.b64encode(img_file.read())
my_string = my_string.decode('utf-8')

然后它工作。但是我的图像没有保存在内存中。而且我不想保存它,因为它会降低程序的速度。

4

2 回答 2

2

您可以在内存中将 RGB 直接编码为 jpg 并为此创建 base64 编码。

jpg_img = cv2.imencode('.jpg', img)
b64_string = base64.b64encode(jpg_img[1]).decode('utf-8')

完整示例:

import cv2
import base64
img = cv2.imread('test_image.jpg')
jpg_img = cv2.imencode('.jpg', img)
b64_string = base64.b64encode(jpg_img[1]).decode('utf-8')

应使用https://codebeautify.org/base64-to-image-converter解码 base 64 字符串

于 2019-12-03T12:52:56.943 回答
0

试试这个方法:- RGB 图像 base64 编码/解码

def encode_img(img_fn):
with open(img_fn, "rb") as f:
data = f.read()
return data.encode("base64")

import cStringIO
import PIL.Image

def decode_img(img_base64):
decode_str = img_base64.decode("base64")
file_like = cStringIO.StringIO(decode_str)
img = PIL.Image.open(file_like)
# rgb_img[c, r] is the pixel values.
rgb_img = img.convert("RGB")
return rgb_img
于 2019-12-03T11:46:00.237 回答