WestHealth / pyvis

Python package for creating and visualizing interactive network graphs.
http://pyvis.readthedocs.io/en/latest/
BSD 3-Clause "New" or "Revised" License
1k stars 172 forks source link

Display local image as node in pyvis graph #122

Open ShairozS opened 2 years ago

ShairozS commented 2 years ago

I would like to visualize a Network where nodes are local images. I see that I can add an image to a node by the following for example:

N.add_node(0, shape='image', image ="https://www.w3schools.com/w3css/img_lights.jpg")

But I see under the documentation that when the shape='image' option is used the image must be the URL to an image. Is there support (or planned support) for using local images, for example passing a PIL Image object into the image parameter?

ShairozS commented 2 years ago

Any updates on this?

Ahmux2018 commented 2 years ago

This works well N.addnode(0, shape='image', image ="file://C:/project/images/imagefile.jpg")

sidml commented 2 years ago

@Ahmux2018 Thanks. It seems we also have to set shape parameter to 'image' otherwise the image isn't displayed.

magralo commented 2 years ago

Which version are you using? it does not work on my pc

magralo commented 2 years ago

Oh! nvm... it works on the html file but not on the notebook

roman-bushuiev commented 1 year ago

Hi, is it possible to directly use a PIL Image object? Unfortunately, I get an error TypeError: Object of type PngImageFile is not JSON serializable. Thank you.

roman-bushuiev commented 1 year ago

It works by encoding the image with base64.b64encode.

ujamshed commented 1 year ago

@roman-bushuiev I am working with a PIL Image object but when I am encoding with base64.b64encode I get a TypeError: Object of type bytes is not JSON serializable. My original error when using the PIL image object directly was TypeError: Object of type Image is not JSON serializable, any advice?

Tanner-Ray-Martin commented 1 year ago

I cam across the same issue as @ujamshed regarding the JSON serialization error. Rather than setting the image as a PIL image, set the image as a filepath: shape='image', image ="file://C:/project/images/imagefile.jpg" as @Ahmux2018 mentioned above in https://github.com/WestHealth/pyvis/issues/122#issuecomment-1080002052.

selflein commented 1 month ago

Took me while to figure out so sharing it here.

Minimal working example to use a PIL Image directly:

from pyvis.network import Network
import base64
from PIL import Image
import io

net = Network(notebook=True, cdn_resources='in_line')

img_bytes_io = io.BytesIO()
Image.open("/tmp/0.png").save(img_bytes_io, "png")
net.add_node(
    0, 
    shape="image",
    image="data:image/png;base64," + base64.b64encode(img_bytes_io.getvalue()).decode("ascii")
)

net.show("test.html")