thiirane
thiirane

Reputation: 45

Importing images from Github to Colab

I am having trouble importing my own images to https://colab.research.google.com/github/vijishmadhavan/Light-Up/blob/master/ArtLine.ipynb#scrollTo=eOhPqC6fysD4.

I am able to execute the sample images (e.g., https://wallpapercave.com/wp/wp2504860.jpg), but when I copy the same image and put it into my own Github repository (https://github.com/thiirane/Artline_images/blob/main/wp2504860.jpg), I get this error.

Here is the Code

#url = 'https://wallpapercave.com/wp/wp2504860.jpg' #@param {type:"string"}
url='https://github.com/thiirane/Artline_images/blob/main/wp2504860.jpg'#@param {type:"string"}
from google.colab import files
from PIL import Image
from IPython.display import Image

#uploaded = files.upload()
response = requests.get(url)

img= PIL.Image.open(BytesIO(response.content)).convert("RGB")
img_t = T.ToTensor()(img)
img_fast = Image(img_t)
show_image(img_fast, figsize=(8,8), interpolation='nearest');

Here is the error:

UnidentifiedImageError                    Traceback (most recent call last)
<ipython-input-18-5d0fa6dc025f> in <module>()
      8 response = requests.get(url)
      9 
---> 10 img= PIL.Image.open(BytesIO(response.content)).convert("RGB")
     11 img_t = T.ToTensor()(img)
     12 img_fast = Image(img_t)

/usr/local/lib/python3.6/dist-packages/PIL/Image.py in open(fp, mode)
   2860         warnings.warn(message)
   2861     raise UnidentifiedImageError(
-> 2862         "cannot identify image file %r" % (filename if filename else fp)
   2863     )
   2864 

UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7fb88126f0f8>

I would be grateful for your help. It is likely something that I am not doing to allow Colab to access my repository.

Upvotes: 0

Views: 2132

Answers (1)

Andrew Chisholm
Andrew Chisholm

Reputation: 6567

It's because the URL is not the direct download link. Use this instead.

import requests
from io import BytesIO
from PIL import Image
url = 'https://raw.githubusercontent.com/thiirane/Artline_images/main/wp2504860.jpg'
page = requests.get(url)
Image.open(BytesIO(page.content))

Or you could use git to download your repository containing images.

!git clone https://github.com/thiirane/Artline_images.git images
from PIL import Image
Image.open('images/wp2504860.jpg')

Upvotes: 2

Related Questions