Aswiderski
Aswiderski

Reputation: 166

Opening image from github with python PIL image.open()

I am hoping to classify some line drawings with a pretrained resnet model and am loading them from a github page. I think the error is coming from me setting up the location of the file wrong, but any help would be appreciated.

The link for the github is here

Here is my code:

loc = 'https://github.com/AlexSwiderski/Images/tree/main/pnt'
fname1 = 'ambulance_resized.png'
response = requests.get(loc + fname1)
image = Image.open(BytesIO(response.content)).resize((256, 256))
data = torch.from_numpy(np.asarray(image)[:, :, :3]) / 255.

My error is as follows:

UnidentifiedImageError                    Traceback (most recent call last)
<ipython-input-29-6e447d67525f> in <module>()
      4 fname1 = 'ambulance_resized.png'
      5 response = requests.get(loc + fname1)
----> 6 image = Image.open(BytesIO(response.content)).resize((256, 256))
      7 data = torch.from_numpy(np.asarray(image)[:, :, :3]) / 255.
      8 

/usr/local/lib/python3.7/dist-packages/PIL/Image.py in open(fp, mode)
   2894         warnings.warn(message)
   2895     raise UnidentifiedImageError(
-> 2896         "cannot identify image file %r" % (filename if filename else fp)
   2897     )
   2898 

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

Upvotes: 0

Views: 575

Answers (1)

Krishay R.
Krishay R.

Reputation: 2814

You need add a slash before the string, otherwise the concatenated path would be

"https://github.com/AlexSwiderski/Images/tree/main/pntambulance_resized.png"

Which is invalid.

loc = 'https://github.com/AlexSwiderski/Images/tree/main/pnt'
fname1 = '/ambulance_resized.png'
response = requests.get(loc + fname1)
image = Image.open(BytesIO(response.content)).resize((256, 256))
data = torch.from_numpy(np.asarray(image)[:, :, :3]) / 255.

Upvotes: 2

Related Questions