Question

Change IPython working directory Inserting image into IPython notebook markdown

Hi, I've read the two above links, and the second link seems most relevant. what the person describes - simply calling the subdirectory - doesn't work for me. For instance, I have an image 'gephi.png' in '/Graphs/gephi.png' But when I write the following

from IPython.display import Image
path = "/Graphs/gephi.png"
i = Image(path)
i

no image pops up - Yup. No error. Just nothing pops up besides an empty square box image.

Clarification: When I move the image to the regular director, the image pops up fine. My only code change is path = "gephi.png"

Was it helpful?

Solution

IPython's Image display object takes three kinds of arguments

The first is raw image data (e.g. the results of open(filename).read():

with open("Graphs/graph.png") as f:
    data = f.read()
Image(data=data)

The second model is to load an image from a filename. This is functionally the same as above, but IPython does the reading from the file:

Image(filename="Graphs/graph.png")

The third form is passing URLs. External URLs can be used, but relative URIs will serve files relative to the notebook's own directory:

Image(url="Graphs/graph.png")

Where this can get confusing is if you don't tell IPython which one of these you are specifying, and you just pass the one argument positionally:

Image("Graphs/graph.png")

IPython tries to guess what you mean in this case:

  1. if it looks like a path and points to an existing file, use it as a filename
  2. if it looks like a URL, use it as a URL
  3. otherwise, fallback on embedding the string as raw png data

That #3 is the source of the most confusion. If you pass it a filename that doesn't exist, you will get a broken image:

Image("/Graphs/graph.png")

Note that URLs to local files must be relative. Absolute URLs will generally be wrong:

Image(url="/Graphs/graph.png")

An example notebook illustrating these things.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top