Search code examples
pythonplotlybytecodefolium

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).

I want to convert this byte object representing a PNG image, to numpy array so it can be used in Folium as image overlay.

Here is an example:

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)

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.


Solution

  • Got a working answer at Plotly Forums:

    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)