python-3.x - 发送OpenCV图像并使用base64解码 : why not compatible?

标签 python-3.x sockets base64 opencv3.0 opencv python

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

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/

相关文章:

python-3.x - 如何切片pandas.DatetimeIndex?

python - 如何从列表中删除重复键

python-3.x - 使用scipy的solve_ivp求解非线性摆运动

python - 石头,布,剪刀,蜥蜴,spock游戏在gui python中

C 套接字客户端/服务器滞后

C select总是检测到套接字可读

javascript - 适用于 C 和 Javascript 的 Base64 库

java - 当我从 android 刷新时出现 Android TCP 错误 :onClick

C - 将 base64 方法添加到我的文件中

java - 如何在java中以无符号方式将字节数组转换为Base 64字符串?