【问题标题】:Base64 to nparray and viceversa as fast as possibleBase64 到 np 数组,反之亦然,尽可能快
【发布时间】:2021-08-13 01:09:25
【问题描述】:

目前我的 Python 服务器接收 base64 编码的 PNG 图像并将其转换为 nparray,如下所示:

input = data['frame'].split(",")[1]
img_data = base64.b64decode(input)
nparr = np.frombuffer(img_data, np.uint8)
img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

反之亦然:

retval, buffer = cv2.imencode('.jpg', output)
pic_str = base64.b64encode(buffer)
pic_str = pic_str.decode()
image_data = "data:image/jpeg;base64," + pic_str

但是,我的实时应用程序花费了太多时间,是否存在更快的方法来做到这一点?在这两个操作之间,nparray 被转换为张量(反之亦然),因此 base64 张量转换也可以。

【问题讨论】:

  • 不编码成base64,发送二进制数据怎么样?
  • 我已经尝试过,但是从客户端发送(和接收)原始数据并从下面的答案中跳过解码/编码部分迫使我在使用之前将图像显式转换为 RGB 图像我的操作和花费的时间减慢了整个过程。
  • 你把事情搞混了。我的意思是不进行 base64 编码/解码,但如果需要,请执行通道顺序转换。
  • 对不起,我没有正确解释自己。如果我将二进制数据发送到服务器并将其作为图像打开,我不会得到 RGB 图像(使用 BytesIo 和图像),将其转换为我想要的操作会花费太多时间。
  • 那么您应该调查为什么会发生这种情况。在任何情况下,base64 转换都是一个附加步骤,而不是必要步骤,因此您应该避免这种情况。 imencode/imdecode 在纯位图数据和压缩数据(例如 JPEG)之间进行转换。这些功能根本不需要任何 b64 编码。看看你是否可以避免“data:image/jpeg;base64”的东西并发送二进制数据,即在你做b64encode之前你拥有的数据

标签: python python-3.x tensorflow opencv base64


【解决方案1】:

速度更新将取决于输入图像的大小。但是以下方法对我来说效果更快:

  • 编码

    def arr_to_base64(image: np.ndarray, ext='jpeg'):
        """ Convert an array to an image source that can be displayed."""
        image = Image.fromarray(image)
        if ext == 'jpg': ext = 'jpeg'
        if ext == 'jpeg' and image.mode in ('RGBA', 'A'):
            background = Image.new(image.mode[:-1], image.size, (255, 255, 255))
            background.paste(image, image.split()[-1])
            image = background
    
        buffer = io.BytesIO()
        image.save(buffer, format=ext)
        encoded = base64.b64encode(buffer.getvalue()).decode('utf-8')
        return f'data:image/{ext};base64,' + encoded
    
  • 解码

    def arr_from_base64(base_string):
        msg = base64.b64decode(base_string[23:])  # Chop of metadata from above
        buf = io.BytesIO(msg)
        img = Image.open(buf)
        return np.array(img)
    

以下测试已针对随机输入图像 (np.random.randint(0, 255, (n, n, 3), dtype=np.uint8)) 运行 100 次。

对(n, n, 3) 图像进行 100 次编码:

对(n, n, 3) 图像进行 100 次编码和解码:

注意事项

  • 请不要使用内置变量 (input)。
  • 在这方面花费的时间似乎并不重要。对于 512 x 512 的大图像,您仍然可以每秒运行大约 80 张图像。您需要大约 23 岁才能获得良好的现实生活饲料。也许您想查看实时排水量。

【讨论】:

  • 这实际上给了我一点改进,感谢您提供的其他提示。
猜你喜欢
  • 2016-03-08
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 2010-11-10
  • 1970-01-01
  • 1970-01-01
  • 2017-05-22
  • 1970-01-01
相关资源
最近更新 更多