48

I am working with a Google Colaboratory notebook. I uploaded a file named bp.png into the working directory, and I can see that the file is in there by running !ls in a code cell. Then I try this piece of code to see the image in a markdown cell:

<h2 align="center">Image</h2>
<img src="bp.png" width="600">

But the Colab notebook's cell stays empty after running that (except for the header), although if I run this in a local Jupyter notebook the image does appear in the cell in that local notebook.

UPDATE:

I know I can use files uploaded to the working directory because my custom .py files that I upload, get imported to my Colab notebooks without any problems. For example, I can upload a file py_file.py and then in the Colab notebook use it as in from py_file import some_function, and it works.

Sergey Zakharov
  • 1,493
  • 3
  • 21
  • 40

4 Answers4

95

Try this

from IPython.display import Image
Image('bp.png')

You can set width and height as well

Image("bp.png", width=100, height=100)

To display more than 1 image, you need to call display. (it’s auto for just 1 image)

from IPython.display import Image, display
display(Image('1.png'))
display(Image('2.png'))

Update jan/2019

Put your image in /usr/local/share/jupyter/nbextensions/

Then display it from /nbextensions/, e.g.

%%html
<img src='/nbextensions/image.png' />

Update feb/2022

In Google Colab, open the file browser icon (left nav bar) and navigate to usr/local/share/jupyter/nbextensions as described above. Click the ellipsis menu on the nbextensions folder > Upload and select your image to upload. Make sure to update the img tag from the code snippet above with the correct file name, and you'll want to use a code box (not text). Note that your image will be deleted from the directory when your runtime is recycled (I got a warning dialog stating so when I uploaded my image), so be careful with that.

Danny Bullis
  • 3,043
  • 2
  • 29
  • 35
korakot
  • 37,818
  • 16
  • 123
  • 144
  • Works like a charm. Thanks! And [here](https://stackoverflow.com/a/35061341/4541649) is how one could display more than one image within a single cell. – Sergey Zakharov Mar 26 '18 at 09:58
  • I add the example for 2 images. – korakot Mar 27 '18 at 03:54
  • the original poster wanted to use a markdown cell. I have the same problem; the proposed solution is using a code cell; I have noticed the markdown img tag works with an url, but not with a local path; Is there a way to find an equivalent url for a file path known to lead to the correct file? `

    Image

    ` works, but not with `/tmp/image.png` or other
    – mrauto Jun 04 '18 at 15:41
  • 1
    @mrauto I think it's impossible. The uploaded file is not on a public web server. You don't have the IP or URL to use to access the file. You can try to send the file to some other web server first, then get its URL there. It's too much of a hassle. – korakot Jun 04 '18 at 17:07
  • @korakot-chaovavanich ok, so no url possible; is there a way to get it to accept a path (relative or absolute), like IPython "Image", using some IPython magic maybe? – mrauto Jun 04 '18 at 17:31
  • I could not figure out the path. Assuming my Jupyter notebook is in Google Drive `My Drive > Colab Notebooks > Foo`, and if I drop a `test.png` file into the same folder, shouldn't the path just be a local `test.png`? I tried that and it did not work. – leeyuiwah Oct 03 '18 at 13:55
  • What if I want to show an image hold as a `numpy` array? – roschach Oct 24 '18 at 16:00
  • @FrancescoBoi You can use matplotlib's imshow. `plt.imshow(img)` – korakot Oct 24 '18 at 23:09
  • I would suggest agains `plt.imshow` because it downsamples the image. Instead, display it with `PIL.Image.fromarray(np_image.astype(np.uint8))`, which creates a PIl image that the notebook knows how to show at native resolution. – Ciprian Tomoiagă Apr 26 '19 at 12:34
  • Btw , jpg images aren't being shown by this command – Sihat Afnan Oct 22 '20 at 20:03
  • @mrauto You can display images within a markdown cell in Colab! Create a Text cell and then you will have a top bar with icons. Select the image icon corresponding to "Insert images" and then choose from you local machine the image. It seems like it doesn't let you select from the google drive, though – NeStack Feb 18 '21 at 21:09
  • Make sure you have the right path to the image. You can get the path by mounting your drive and then right-clicking on the desired file needed. – Delicia Fernandes Sep 22 '21 at 07:21
  • In Google Colab, open the file browser icon (left nav bar) and navigate to `usr/local/share/jupyter/nbextensions` as described above. Click the ellipsis menu on the `nbextensions` folder > Upload and select your image to upload. Make sure to update the `img` tag from the code snippet above with the correct file name, and you'll want to use a *code* box (not text). Note that your image will be deleted from the directory when your runtime is recycled (I got a warning dialog stating so when I uploaded my image), so be careful with that. – Danny Bullis Feb 02 '22 at 06:56
7

One can also display images in the markdown/Text cell in Colab. Create a Text cell and then you will have a top bar with icons. Select the image icon corresponding to "Insert images" and then choose from you local machine the image. It seems like it doesn't let you select from the google drive, though

enter image description here

NeStack
  • 1,739
  • 1
  • 20
  • 40
2

Here's a function that can display an image file from any directory.

Note that this function produces the same result as IPython.display.Image, though.

from IPython.display import HTML
from base64 import b64encode

def show_image(path_to_image, width=None, height=None):

    mime_type = None
    path_to_image = path_to_image.lower()

    # More MIME types:
    # https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types
    if path_to_image.endswith('.jpg') or path_to_image.endswith('.jpeg'):
        mime_type = 'image/jpeg'
    elif path_to_image.endswith('.png'):
        mime_type = 'image/png'
    elif path_to_image.endswith('.gif'):
        mime_type = 'image/gif'
    else:
        raise ValueError('Unknown extension: %s' % (path_to_image))

    img = open(path_to_image, 'rb').read()
    data_url = 'data:image/jpeg;base64,' + b64encode(img).decode()

    width_str = "width='%d'" % (width) if width is not None else ''
    height_str = "height='%d'" % (width) if height is not None else ''

    display(HTML("<img src='%s' %s%s>" % (data_url, width_str, height_str)))

Example:

show_image('frames/frame_1000.jpg', width=300)

enter image description here

stackoverflowuser2010
  • 38,621
  • 48
  • 169
  • 217
1

I tried below and it worked

from google.colab import drive
drive.mount ('/content/drive')

After mounting the drive, use following code

from IPython.display import Image
Image(filename='/content/drive/MyDrive/filename.jpg',width=500,height=500)
Rafael Z. B. Bravo
  • 1,022
  • 10
  • 23