将 numpy 数组转换为可由 html img 标签的 src 读取的字节串

Convert numpy array into a bytestring readable by the src of an html img tag

我有一个 numpy 数组,我想通过 img html 组件的 src 属性显示它,有点像这个例子:

def get_placeholder_thumbnail_html_value():
    encoded_image = base64.b64encode(open("../assets/placeholder_thumbnail.png", 'rb').read())
    return 'data:image/png;base64,{}'.format(encoded_image.decode())

然后可以发送返回的字符串以分配给相应 img html 组件的 src 属性(我使用 plotly dash 回调来实现)。

问题:在上面的示例中,我是从服务器上的 png 图像做的。 我怎样才能从 numpy ndarray 做同样的事情?

def get_thumbnail_html_value_from_ndarray(ndarray):
    return 'data:image/png;base64,{}'.format(<what here ?>)

它可以解析为 jpg 或其他任何格式,只要 html 可以正确解释图像。

编辑:我可以将其作为 png 文件保存在服务器上,然后使用上面的示例将其加载回来,但它似乎效率很低,所以我不喜欢这种解决方法。

我遇到了基本相同的问题,附加条件是图像格式需要为 png。这是我使用 cv2 和 base64 的解决方案:

import cv2
import base64

def ndarray_to_b64(ndarray):
    """
    converts a np ndarray to a b64 string readable by html-img tags 
    """
    img = cv2.cvtColor(ndarray, cv2.COLOR_RGB2BGR)
    _, buffer = cv2.imencode('.png', img)
    return base64.b64encode(buffer).decode('utf-8')