320

I would like to use an IPython notebook as a way to interactively analyze some genome charts I am making with Biopython's GenomeDiagram module. While there is extensive documentation on how to use matplotlib to get graphs inline in IPython notebook, GenomeDiagram uses the ReportLab toolkit which I don't think is supported for inline graphing in IPython.

I was thinking, however, that a way around this would be to write out the plot/genome diagram to a file and then open the image inline which would have the same result with something like this:

gd_diagram.write("test.png", "PNG")
display(file="test.png")

However, I can't figure out how to do this - or know if it's possible. So does anyone know if images can be opened/displayed in IPython?

Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
zach
  • 29,475
  • 16
  • 67
  • 88

16 Answers16

531

Courtesy of this post, you can do the following:

from IPython.display import Image
Image(filename='test.png') 
9769953
  • 10,344
  • 3
  • 26
  • 37
zach
  • 29,475
  • 16
  • 67
  • 88
  • It'd better use public API without accessing internals: `from IPython.display import Image` should work since 0.13. – tomyun Dec 16 '14 at 01:05
  • 88
    this does not display image if inside a loop – muon Jan 23 '16 at 21:00
  • 9
    Most people would want DrMcCleod's answer. – AturSams Jan 23 '17 at 16:19
  • 6
    This only works for me if I pass Image(filename='test.png') to display, as recommended in a thread below: `from IPython.core.display import Image, display` `display(Image(filename='test.png'))` – John Strong Aug 20 '17 at 00:37
  • 1
    In case you want the image to also show in slides presentation mode ( which you run with `jupyter nbconvert mynotebook.ipynb --to slides --post serve`) then the image path should start with `/` so that it is an absolute path from the web root, i.e. `![alt text](/test.jpg "Some Title")` – ccpizza Jun 28 '18 at 17:43
  • is it possible to display the image, along with markdown in the same output cell using Image? Also can image be resized? – alancalvitti Jul 21 '21 at 16:58
  • Beware of conflicts between `IPython.display.Image` and `PIL.Image` if you need the latter later. – Skippy le Grand Gourou Dec 26 '22 at 12:08
314

If you are trying to display an Image in this way inside a loop, then you need to wrap the Image constructor in a display method.

from IPython.display import Image, display

listOfImageNames = ['/path/to/images/1.png',
                    '/path/to/images/2.png']

for imageName in listOfImageNames:
    display(Image(filename=imageName))
DrMcCleod
  • 3,865
  • 1
  • 15
  • 24
  • 7
    Why? (Don't tell me that otherwise it doesn't work. Please explain why this call to 'display' is needed in a loop but not if you just dispaly one image). – Kris May 01 '17 at 01:25
  • 31
    Because IPython Notebooks only show the last return value in a cell, so whenever you have two outputs from the same cell you will need to use the 'display' method. See [this question](http://stackoverflow.com/questions/34398054/ipython-notebook-cell-multiple-outputs) for more. – DrMcCleod May 01 '17 at 22:20
  • 2
    You are my hero - I've been looking for this for two days. – ZaxR Oct 15 '17 at 06:23
  • 1
    This is great. How would I make the next image replace the existing one, like for an animated effect as an image changes over time ? – blissweb Nov 19 '18 at 21:19
  • 3
    I was wondering, how could we tile the images? For instance to show a 4x4 group of images. – gmagno May 23 '19 at 14:45
52

Note, until now posted solutions only work for png and jpg!

If you want it even easier without importing further libraries or you want to display an animated or not animated GIF File in your Ipython Notebook. Transform the line where you want to display it to markdown and use this nice short hack!

![alt text](test.gif "Title")
Philipp Schwarz
  • 18,050
  • 5
  • 32
  • 36
36

This will import and display a .jpg image in Jupyter (tested with Python 2.7 in Anaconda environment)

from IPython.display import display
from PIL import Image


path="/path/to/image.jpg"
display(Image.open(path))

You may need to install PIL

in Anaconda this is done by typing

conda install pillow
conor
  • 1,131
  • 1
  • 15
  • 20
  • 1
    Cleanest solution IMO as it is short, prevents conflicts between `IPython.display.Image` and `PIL.Image` if you need PIL, and each action is explicit (`display` & `open`). – Skippy le Grand Gourou Dec 26 '22 at 12:07
27

If you want to efficiently display big number of images I recommend using IPyPlot package

import ipyplot

ipyplot.plot_images(images_array, max_images=20, img_width=150)

enter image description here

There are some other useful functions in that package where you can display images in interactive tabs (separate tab for each label/class) which is very helpful for all the ML classification tasks.

enter image description here

Karol Żak
  • 2,158
  • 20
  • 24
  • 1
    This has some rendering issues on a single image, cannot magnify correctly (displayed contents do not grow to fit the magnified image)... – Piotr Dabkowski Jan 31 '22 at 12:42
  • 1
    Interesting! Thanks for info @PiotrDabkowski! I'm quite bad with HTML and CSS so it's entirely possible I hacked it poorly :). Nevertheless, would you mind adding an issue in the repo -> https://github.com/karolzak/ipyplot – Karol Żak Jan 31 '22 at 13:16
22

You could use in html code in markdown section: example:

 <img src="https://www.tensorflow.org/images/colab_logo_32px.png" />
Moumen Lahmidi
  • 462
  • 5
  • 7
  • simple and best!, you can add it in `.ipnb` markdown section or in `README.md` referencing the path of the image relative to the project directory. `` – Anu Sep 23 '21 at 22:07
17

A cleaner Python3 version that use standard numpy, matplotlib and PIL. Merging the answer for opening from URL.

import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

pil_im = Image.open('image.png') #Take jpg + png
## Uncomment to open from URL
#import requests
#r = requests.get('https://www.vegvesen.no/public/webkamera/kamera?id=131206')
#pil_im = Image.open(BytesIO(r.content))
im_array = np.asarray(pil_im)
plt.imshow(im_array)
plt.show()
Punnerud
  • 7,195
  • 2
  • 54
  • 44
12

Courtesy of this page, I found this worked when the suggestions above didn't:

import PIL.Image
from cStringIO import StringIO
import IPython.display
import numpy as np
def showarray(a, fmt='png'):
    a = np.uint8(a)
    f = StringIO()
    PIL.Image.fromarray(a).save(f, fmt)
    IPython.display.display(IPython.display.Image(data=f.getvalue()))
Afflatus
  • 2,302
  • 5
  • 25
  • 40
9
from IPython.display import Image

Image(filename =r'C:\user\path')

I've seen some solutions and some wont work because of the raw directory, when adding codes like the one above, just remember to add 'r' before the directory. this should avoid this kind of error: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

Magno Naoli
  • 91
  • 1
  • 1
5

If you are looking to embed your image into ipython notebook from the local host, you can do the following:

First: find the current local path:

# show current directory
import os
cwd = os.getcwd()
cwd

The result for example would be:

'C:\\Users\\lenovo\\Tutorials'

Next, embed your image as follows:

from IPython.display import display
from PIL import Image

path="C:\\Users\\lenovo\\Tutorials\\Data_Science\\DS images\\your_image.jpeg"
display(Image.open(path))

Make sure that you choose the right image type among jpg, jpeg or png.

Taie
  • 1,021
  • 16
  • 29
2

Another option for plotting inline from an array of images could be:

import IPython
def showimg(a):
    IPython.display.display(PIL.Image.fromarray(a))

where a is an array

a.shape
(720, 1280, 3)
2

You can directly use this instead of importing PIL

from IPython.display import Image, display
    
    display(Image(base_image_path))
    
Mohamed Fathallah
  • 1,274
  • 1
  • 15
  • 17
1

Another opt is:

from matplotlib import pyplot as plt 
from io import BytesIO
from PIL import Image
import Ipython

f = BytesIO()
plt.savefig(f, format='png')
Ipython.display.display(Ipython.display.Image(data=f.getvalue()))
f.close()
Nhu Phan
  • 699
  • 7
  • 4
0

When using GenomeDiagram with Jupyter (iPython), the easiest way to display images is by converting the GenomeDiagram to a PNG image. This can be wrapped using an IPython.display.Image object to make it display in the notebook.

from Bio.Graphics import GenomeDiagram
from Bio.SeqFeature import SeqFeature, FeatureLocation
from IPython.display import display, Image
gd_diagram = GenomeDiagram.Diagram("Test diagram")
gd_track_for_features = gd_diagram.new_track(1, name="Annotated Features")
gd_feature_set = gd_track_for_features.new_set()
gd_feature_set.add_feature(SeqFeature(FeatureLocation(25, 75), strand=+1))
gd_diagram.draw(format="linear", orientation="landscape", pagesize='A4',
                fragments=1, start=0, end=100)
Image(gd_diagram.write_to_string("PNG"))

[See Notebook]

Quantum7
  • 3,165
  • 3
  • 34
  • 45
0

You might use markdown cell with the following content:

![alternate image name](path/to/image_file)

Yinon Ehrlich
  • 586
  • 6
  • 14
-1

This is the solution using opencv-python, but it opens new windows which is busy in waiting

import cv2 # pip install opencv-python
image = cv2.imread("foo.png")
cv2.imshow('test',image)
cv2.waitKey(duration) # in milliseconds; duration=0 means waiting forever
cv2.destroyAllWindows()

if you don't want to display image in another window, using matplotlib or whatever instead cv2.imshow()

import cv2
import matplotlib.pyplot as plt
image = cv2.imread("foo.png")
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()
Community
  • 1
  • 1
Deep
  • 1
  • 1
  • You need to provide more context to your solution. Why would you want to use this? And where does `cv2` come from? – expelledboy Mar 21 '22 at 13:21