Using Local Image as Background Image

I am trying to set an image that I have stored locally as the background for a heatmap. I followed the example at https://plot.ly/python/images/ and I am able to show a web-addressed image as the background image for my heatmap, but when I use a local image (both relative and absolute address) the image does not show and no error message is indicated. The reference (https://plot.ly/python/reference/#layout-images-source) doesn’t say anything about this address being restricted to web addresses. I am using plotly offline and my code is below.

    trace1 = dict(z=np.flipud(vals),
              type="heatmap",
              zmin=0.0,
              zmax=1.0,
              colorscale='YlOrRd',
              opacity= 0.5)

# source_image_url = '/home/hannahrae/data/05092017/' + img_name + '.png' (this is the one that doesn't work
source_image_url = 'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/FullMoon2010.jpg/800px-FullMoon2010.jpg'
print source_image_url
layout = go.Layout(images=[dict(source=source_image_url,
                           xref= "x",
                           yref= "y",
                           x= 0,
                           y= h,
                           sizex= w,
                           sizey= h,
                           sizing= "stretch",
                           opacity= 0.5,
                           layer= "below")],
                    title= ("Probability of Quality Acceptance Across Image for %s", d))

fig = go.Figure(data=[trace1], layout=layout)
py.plot(fig)
2 Likes

It seems really strange that this is not resolved. Are there any updates on this feature?

Edit: this is slightly related: https://github.com/plotly/dash/issues/71

Hi, I followed the github advise, but the image is still not showing up in plotly graph, whereas the example images do. Please advise. This is my code:

“images”: [{ “source”: “images”: [{ “source”: “https://github.com/amanbadhwar/test_images/blob/master/cer.png”,
“xref”: “paper”,
“yref”: “paper”,
“x”: 1,
“y”: 1,
“sizex”: 1,
“sizey”: 1,
“xanchor”: “right”,
“yanchor”: “bottom”}],

The source field can be a PIL.Image.Image.

Modifying the code at https://plot.ly/python/images/

import plotly.plotly as py
import plotly.graph_objs as go

import numpy as np
from PIL import Image

image_array = np.random.randint(0, 255, size=(100, 100)).astype('uint8')
image = Image.fromarray(image_array)


trace1= go.Scatter(x=[0,0.5,1,2,2.2],y=[1.23,2.5,0.42,3,1])
layout= go.Layout(images= [dict(
                  source= image,
                  xref= "x",
                  yref= "y",
                  x= 0,
                  y= 3,
                  sizex= 2,
                  sizey= 2,
                  sizing= "stretch",
                  opacity= 0.5,
                  layer= "below")])
fig=go.Figure(data=[trace1],layout=layout)
py.iplot(fig,filename='EXAMPLES/background')

Should add an image of random values as a background. Pretty!

1 Like

Tank you for all this idea.
I try to use plotly for exploit a timelapse series. I use a code very similar as above but i add "updatemenus " in my layout.
When I add that I have this error:
TypeError: <PIL.Image.Image image mode=L size=100x100 at 0x7F39B0282650> is not JSON serializable
Do you have and Idea in my case.
Thank

import numpy as np
import plotly.graph_objs as go
import plotly as ply
from PIL import Image

"Images"
image_array = np.random.randint(0, 255, size=(100, 100)).astype('uint8')
image1 = Image.fromarray(image_array)

image_array = np.random.randint(0, 255, size=(100, 100)).astype('uint8')
image2 = Image.fromarray(image_array)

image_array = np.random.randint(0, 255, size=(100, 100)).astype('uint8')
image3 = Image.fromarray(image_array)


"""------------------Images Weeb Cam---------------------------"""


img_width = 2560
img_height = 1920
scale_factor = 0.2

layout = go.Layout(
    xaxis = go.layout.XAxis(
        visible = False,
        range = [0, img_width*scale_factor]),
    yaxis = go.layout.YAxis(
        visible=False,
        range = [0, img_height*scale_factor],

        scaleanchor = 'x'),
    width = img_width*scale_factor,
    height = img_height*scale_factor,
    margin = {'l': 0, 'r': 0, 't': 0, 'b': 0},
    
    images =[dict(
        visible=True,
        x=0,
        sizex=img_width*scale_factor,
        y=img_height*scale_factor,
        sizey=img_height*scale_factor,
        xref="x",
        yref="y",
        opacity=1.0,
        layer="below",
        sizing="stretch",
        source=image1)
        ]

)
    
cluster0 = [dict(
            visible=True,
            x=0,
            sizex=img_width*scale_factor,
            y=img_height*scale_factor,
            sizey=img_height*scale_factor,
            xref="x",
            yref="y",
            opacity=1.0,
            layer="below",
            sizing="stretch",
            source=image1)]
cluster1 = [dict(
            visible=True,
            x=0,
            sizex=img_width*scale_factor,
            y=img_height*scale_factor,
            sizey=img_height*scale_factor,
            xref="x",
            yref="y",
            opacity=1.0,
            layer="below",
            sizing="stretch",
            source=image2)]
cluster2 = [dict(
            visible=True,
            x=0,
            sizex=img_width*scale_factor,
            y=img_height*scale_factor,
            sizey=img_height*scale_factor,
            xref="x",
            yref="y",
            opacity=1.0,
            layer="below",
            sizing="stretch",
            source=image3)]


    
updatemenus = list([
    dict(type="buttons",
         buttons=list([   
            dict(label = 'Image n',
                 method = 'relayout',
                 args = ['images', cluster0]),
            dict(label = 'Image n-1',
                 method = 'relayout',
                 args = ['images', cluster1]),
            dict(label = 'Image n-2',
                 method = 'relayout',
                 args = ['images', cluster2])
        ]),
    )
])
    
layout['updatemenus'] = updatemenus   
# we add a scatter trace with data points in opposite corners to give the Autoscale feature a reference point
fig = go.Figure(data=[{
    'x': [0, img_width*scale_factor], 
    'y': [0, img_height*scale_factor], 
    'mode': 'markers',
    'marker': {'opacity': 0}}],layout = layout)

ply.offline.plot(fig, filename='ImChalet',config={'showLink': False})

Hi @RVB,

For each of your images, try replacing

images =[dict(
        ...
        source=image1)]

with

images =[go.layout.Image(
        ...
        source=image1)]

In most cases graph_objs objects are interchangeable with dict instances, but the logic for converting the PIL Image object into a form that plotly.js understands is performed by the go.layout.Image class.

Hope that helps!
-Jon

Thank for your help.

  The result can be visible here.

sincerely

Hervé

I’m having a similar problem!!

If I have the source as a web address it works just fine (left), If I have it as a local image it doesn’t appear. (right)
Any ideas?


here my code:

#left graph
layout = go.Layout(
                height=700,
                hovermode="closest",
                #title='Anillo {}'.format(anillo)
                title='EXTC',
                images= [dict(
                    source="https://images.plot.ly/language-icons/api-home/python-logo.png",
                    xref="paper", yref="paper",
                    x=0.5, y=0.5,
                    sizex=0.5, sizey=0.5,
                    xanchor="center",
                    yanchor="middle",
                    sizing="stretch",
                    layer="above")])

#right graph
import base64

image_filename = 'images/python-logo.png'
imagem_tunel = base64.b64encode(open(image_filename, 'rb').read())

layout = go.Layout(
                height=700,
                hovermode="closest",
                #title='Anillo {}'.format(anillo)
                title='EXTC',
                images= [dict(
                    source='data:image/png;base64,{}'.format(imagem_tunel),
                    xref="paper", yref="paper",
                    x=0.5, y=0.5,
                    sizex=0.5, sizey=0.5,
                    xanchor="center",
                    yanchor="middle",
                    sizing="stretch",
                    layer="above")])


What am I doing wrong?:upside_down_face:

hey @cecilia I think you forgot to decode the file, see my example here Plotly unable to embed a logo or background image in plotly - #25 by Anthony1223?