'How can I open images in a Google Colaboratory notebook cell from uploaded png files?
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.
Solution 1:[1]
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
Solution 2:[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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | NeStack |
| Solution 2 | stackoverflowuser2010 |


