【问题标题】:Send OpenCV image and decode using base64: why not compatible?使用 base64 发送 OpenCV 图像和解码:为什么不兼容?
【发布时间】:2021-08-30 21:58:14
【问题描述】:

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

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 编码中去除前两个字符?

【问题讨论】:

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


    【解决方案1】:

    让我们分析一下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") 去掉切片。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      • 2016-08-18
      • 2017-11-26
      • 2017-03-20
      • 2011-05-07
      相关资源
      最近更新 更多