我需要将图像编码为二进制,将其发送到服务器并再次将其解码回图像。 解码方法为:
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
对象,请参阅 this answer .
实际上,str
表示打印时看到的 bytes
对象,即带有前导 b'
和尾随 '
。
例如
>>> base64.b64encode(bin)
b'/9j/4AAQSkZJRgABAQAAAQABAAD'
>>> str(base64.b64encode(bin))
"b'/9j/4AAQSkZJRgABAQAAAQABAAD'"
这就是为什么您需要删除这些字符才能获得编码字符串。
通常,这不是将 bytes
对象转换为字符串的最佳方法,因为需要编码来指定如何将 bytes
解释为字符。这里的str
函数使用默认的ASCII编码。
如 this answer 中所述,你可以替换
str(base64.b64encode(bin))[2:-1]
与 str(base64.b64encode(bin), "utf-8")
来摆脱切片。
关于python-3.x - 发送OpenCV图像并使用base64解码 : why not compatible?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67979664/