✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🐇 Announcing Dash VTK for 3d simulation graphics. Check out the March webinar.

Converting Byte Object to numpy array

I want to convert the byte object exported with fig.to_image(), to numpy array so it can be used in Folium as image overlay. (I can not save the image to disk)
How can this be done?

Here is an example:

import plotly.graph_objects as go
# Create plot
fig = go.Figure(data =
        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)

I have tried using PIL:

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

Getting ValueError: not enough image data .

I have never used byte object before making this process very confusing for me.

PS: Any other way to use plotly figure on folium map is also appreciated.

Hi @f.batiri

This is the function that converts Plotly fig image to an array:

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)
1 Like

Works like a charm and saved me a lot of time. Thank you very much.

I recently learned how to make this conversion. @jmmease answered my question. Thanks go to him.

1 Like