发送OpenCV图像并使用base64解码:为什么不兼容



我需要将图像编码为二进制,将其发送到服务器,然后再次解码为图像。解码方法为:

def decode_from_bin(bin_data):
bin_data = base64.b64decode(bin_data)
image = np.asarray(bytearray(bin_data), dtype=np.uint8)
img = cv2.imdecode(image, cv2.IMREAD_COLOR)
return img

我们使用OpenCV对图像进行编码:

def encode_from_cv2(img_name):
img = cv2.imread(img_name, cv2.IMREAD_COLOR)  # adjust with EXIF
bin = cv2.imencode('.jpg', img)[1]
return str(base64.b64encode(bin))[2:-1] # Raise error if I remove [2:-1]

您可以使用运行

raw_img_name = ${SOME_IMG_NAME}
encode_image = encode_from_cv2(raw_img_name)
decode_image = decode_from_bin(encode_image)
cv2.imshow('Decode', decode_image)
cv2.waitKey(0)

我的问题是:为什么我们必须从base64编码中去掉前两个字符?

让我们分析一下encode_from_cv2内部发生了什么。

base64.b64encode(bin)的输出是一个bytes对象。当您将它传递给str(base64.b64encode(bin))中的str时,str函数将创建一个";可良好印刷的";bytes对象的版本,请参阅此答案。

在实践中,str表示打印时看到的bytes对象,即带有前导b'和traling'。例如

>>> base64.b64encode(bin)
b'/9j/4AAQSkZJRgABAQAAAQABAAD'
>>> str(base64.b64encode(bin))
"b'/9j/4AAQSkZJRgABAQAAAQABAAD'"

这就是为什么您需要删除这些字符才能获得编码的字符串。

通常,这不是将bytes对象转换为字符串的最佳方式,因为需要进行编码来指定如何将bytes解释为字符。这里的str函数使用默认的ASCII编码。

如本答案所述,您可以将用CCD_ 15和CCD_。

最新更新