Home > other >  Opening image from github with python PIL image.open()
Opening image from github with python PIL image.open()

Time:11-24

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>

CodePudding user response:

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.
  • Related