将 Plotly 图像字节对象转换为 numpy 数组

Convert Plotly image byte object to numpy array

The plotly.io.to_image function is used to return an image as a bytes object (Doc).

我想将这个表示 PNG 图像的字节对象转换为 numpy 数组,以便它可以在 Folium 中用作图像叠加层。

这是一个例子:

import plotly.graph_objects as go
# Create plot
fig = go.Figure(data =
    go.Contour(
        z=[[10, 10.625, 12.5, 15.625, 20],
           [5.625, 6.25, 8.125, 11.25, 15.625],
           [2.5, 3.125, 5., 8.125, 12.5],
           [0.625, 1.25, 3.125, 6.25, 10.625],
           [0, 0.625, 2.5, 5.625, 10]]
    ))
# Export byte object
img_bytes = fig.to_image(format="png",width=600, height=350)

我试过使用 PIL:

from PIL import Image
img = Image.frombytes("RGB", (350,600), img_bytes)

获得ValueError: not enough image data.

在使这个过程对我来说非常混乱之前,我从未使用过字节对象。


PS: 在 folium 地图上使用 plotly figure 的任何其他方式也值得赞赏。

Plotly Forums 得到了有效答案:

这是将 Plotly 无花果图像转换为数组的函数:

import io 
from PIL import Image

def plotly_fig2array(fig):
    #convert Plotly fig to  an array
    fig_bytes = fig.to_image(format="png")
    buf = io.BytesIO(fig_bytes)
    img = Image.open(buf)
    return np.asarray(img)