python - 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
解决方案
推荐阅读
- microsoft-graph-api - Microsoft Graph API - 使用导航链接创建文档库
- python - 使用for循环python打印三角形金字塔图案
- python - 文本在彼此之上pygame
- oracle - 数据库备份后未建立连接
- nuget - Nuget 包版本控制 - 主要/次要/补丁的最大整数?
- javascript - redux 中间件和 redux-observable 史诗之间有什么区别?
- swift - 在 Swift 中制作动画之前,如何对 UILabel 应用变换?
- python - 确定集合列表是否共享数据
- c# - 将二进制文件数据读入结构列表
- python - 在其他 numpy 数组中查找 numpy 数组