Title Image

Adding Images in IPython Notebook (short article)

The current article is about a problem that I had faced when started learning data analysis in the IPython notebook. The problem is about loading an image in IPython notebook so that I could present codes with better visual representation (i.e., with images).

I have searched for several solutions on different websites. Different people have reported different mechanisms and libraries in Q & A blogs. After trying different solutions I have found two possible solutions for both Python and R that works perfectly.

Python solution

Let’s first discuss the solution when running Python in the IPython notebook. We could use the Image class of IPython.display to load and display a local image in the IPython notebook.

Here, I have used the Image( ) function, where one needs to supply the filename i.e., the location path for the image file. Additionally, we can vary the width and height to adjust the image size.

#Import library
from IPython.display import Image
# Load image from local storage
Image(filename = "img1.png", width = 600, height = 300)
Image for post
Photo by Aleks Dorohovich on Unsplash

R Solution

Let’s next discuss the R solution for IPython notebook. For R, IRdisplay library is the best available option to load a local image.

Here, I have used the display_png( ) function, where one needs to supply the filename i.e., the location path for the image file. Additionally, we can vary the width and height to adjust the image size.

#Import library
library("IRdisplay")
# Load image from local storage
display_png(file = "img1.png", width = 600, height = 300)
Image for post
Photo by Aleks Dorohovich on Unsplash

I hope this would help.

2 thoughts on “Inserting and Resizing Images in IPython Notebook (Python and R)

  1. Zhenhua Huang

    I used
    from IPython.display import Image
    Image(filename=’Data/MobileNet-samples/1.jpg’, width=300, height=200)

    It works on my Colab Notebook but not Jupyter Notebook. On Jupyter, the width can be adjusted but the height can not be adjusted. Please advise.

    1. Rahul Raoniar

      Hi! ZHENHUA HUANG,

      Yes, changing height does not have any impact on the image. I have noticed this bug. It exists in the Jupyter notebook environment.

      If I am able to locate any fix, I will post it.

Leave a Reply

Your email address will not be published. Required fields are marked *