首页 > 解决方案 > Python Base64 影响输出数据

问题描述

我遇到了我不理解的 Base64 编码器/解码器问题。我正在传输由以下人员打开的图像:

image = open(IMAGE_PATH, "rb").read()
payload = {"image": image,
           "filename": os.path.basename(IMAGE_PATH),
           "extension": file_extension
r = requests.post(KERAS_REST_API_URL, files=payload).json()

传输后,图像由 REST API 通过以下方式打开:

image = Image.open(io.BytesIO(image))
image = np.asarray(image)

然后传递给 Base64 Encoder => 一切都很好。请参阅下面 Base64 编码器功能的结果

[[29477 29480 29443 ... 29465 29463 29473]
 [29473 29469 29440 ... 29481 29460 29441]
 [29434 29436 29452 ... 29459 29474 29444]
 ...
 [29455 29437 29440 ... 29439 29433 29481]
 [29451 29456 29441 ... 29469 29450 29452]
 [29472 29455 29440 ... 29433 29453 29459]]

[INFO] Image Shape : (768, 1024)
[INFO] Channel : 1
[INFO] Image Shape : (768, 1024)
[INFO] Image Shape Encode : (768, 1024)
[INFO] Image Shape Encode/Decode : (786432,)

我不想通过“open(IMAGE_PATH,”rb“).read()”传输图像,而是想传输一个 Numpy 数组,因为我的图像也将是 dicom 图像。

因此,我使用以下命令打开图像文件:

image = np.asarray(Image.open(IMAGE_PATH))

和有效载荷变成:

payload = {"image": json.dumps(image, cls=NumpyArrayEncoder),
                       "filename": os.path.basename(IMAGE_PATH),
                       "extension": file_extension
                       }
requests.post line is unchanged.

在 REST API 中,读取图像的行变为:

image = request.files["image"].read()
image = json.loads(image)
image = np.asarray(image)

然后传递给 Base64 Encoder,无需对代码进行任何修改。我得到以下结果

[[29477 29480 29443 ... 29465 29463 29473]
 [29473 29469 29440 ... 29481 29460 29441]
 [29434 29436 29452 ... 29459 29474 29444]
 ...
 [29455 29437 29440 ... 29439 29433 29481]
 [29451 29456 29441 ... 29469 29450 29452]
 [29472 29455 29440 ... 29433 29453 29459]]

[INFO] Image Shape : (768, 1024)
[INFO] Channel : 1
[INFO] Image Shape : (768, 1024)
[INFO] Image Shape Encode : (768, 1024)
[INFO] Image Shape Encode/Decode : (1572864,)

最后,我遇到的问题是当我解码数据时,形状不再与预期的形状匹配(高出 2 倍)。

你有什么提示可以解决这个问题吗?

谢谢

def base64_encode_image(a):
    # base64 encode the input NumPy array
    print("[INFO] Image Shape Encode : " + str(a.shape))
    a = base64.b64encode(a).decode("utf-8")
    a = bytes(a, encoding="utf-8")
    a = np.frombuffer(base64.decodebytes(a), dtype='int32')
    print("[INFO] Image Shape Encode/Decode : " + str(a.shape))
    return base64.b64encode(a).decode("utf-8")




def base64_decode_image(a, dtype, shape):
    if sys.version_info.major == 3:
        print("[INFO] Python 3")
        a = bytes(a, encoding="utf-8")
    # convert the string to a NumPy array using the supplied data
    # type and target shape
    a = np.frombuffer(base64.decodestring(a), dtype=dtype)
    print("[INFO] Image Shape Decode : " + str(a.shape))
    a = a.reshape(shape)
    # return the decoded image
    return a

标签: pythonbase64decodeshapesmismatch

解决方案


推荐阅读