[python] How can I display an image from a file in Jupyter Notebook?

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?

This question is related to python jupyter-notebook ipython

The answer is


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")

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)

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

 <img src="https://www.tensorflow.org/images/colab_logo_32px.png" />

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()))

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


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

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))

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


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()

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]


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to jupyter-notebook

How to prevent Google Colab from disconnecting? Jupyter Notebook not saving: '_xsrf' argument missing from post How do I install Python packages in Google's Colab? What is the difference between Jupyter Notebook and JupyterLab? Importing .py files in Google Colab Display all dataframe columns in a Jupyter Python Notebook How to open local file on Jupyter? how to open Jupyter notebook in chrome on windows Change the Theme in Jupyter Notebook? Jupyter notebook not running code. Stuck on In [*]

Examples related to ipython

How to increase image size of pandas.DataFrame.plot in jupyter notebook? Importing .py files in Google Colab Selection with .loc in python IOPub data rate exceeded in Jupyter notebook (when viewing image) Purpose of "%matplotlib inline" Installing a pip package from within a Jupyter Notebook not working convert json ipython notebook(.ipynb) to .py file In which conda environment is Jupyter executing? How to make inline plots in Jupyter Notebook larger? %matplotlib line magic causes SyntaxError in Python script