Render plotly figure as numpy ndarray of rgba pixels

I have a situation where I need to represent a plotly figure as a numpy.ndarray of rgba pixel values.

so far i have been able to do this by

  1. creating an io buffer
  2. writing a PNG to this buffer
  3. using the ioimage to convert this PNG buffer to a numpy array
import io

import imageio.v3 as iio
import plotly.express as px

fig = px.scatter(
    px.data.iris(),
    x="sepal_length",
    y="sepal_width",
    color="species",
)
buf = io.BytesIO()

fig.write_image(
    buf,
    engine="kaleido",
    format="png",
    scale=2,
    width=800,
    height=600,
)

buf.seek(0)

im = iio.imread(buf)
im = im.transpose(2, 0, 1)
print("image shape:", im.shape)
print("image type:", type(im))

is there a more efficient, maybe dependency-free way to achieve this?

Iā€™m using the following function:

import io 
from PIL import Image
def plotly_fig2array(fig):
    #convert a Plotly fig to  a RGBA-array
    fig_bytes = fig.to_image(format="png")
    buf = io.BytesIO(fig_bytes)
    img = Image.open(buf)
    return np.asarray(img)

Now let us check it:

import plotly.express as px
import numpy as np
N = 128
h = 450
I, J= np.indices((N, N))
fig = px.imshow(((I & J) &  (I ^ J) % 9) , color_continuous_scale='speed') 
fig.update_layout(width=h, height=h, xaxis_visible=False, yaxis_visible=False,
coloraxis_showscale=False)

Convert the generated fig to an RGBA-array (i.e. of shape(450, 450, 4)):

rgba_arr=plotly_fig2array(fig)
rgba_arr.shape