使用Python PIL Image.open加载GitHub图片报UnidentifiedImageError如何解决?
问题排查与解决方案
错误原因
你当前使用的路径为GitHub的文件列表网页地址,直接拼接文件名后请求得到的是图片预览页的HTML源码,并非图片本身的二进制数据,因此PIL无法识别该内容,触发UnidentifiedImageError报错。
修复步骤
- 将根路径替换为GitHub原始资源服务地址,正确的根路径为
https://raw.githubusercontent.com/AlexSwiderski/Images/main/pnt/,注意路径末尾需要保留斜杠,避免拼接文件名时出现路径错误。 - 可选添加请求状态校验,提前识别请求失败的场景。
修复后可用代码
import requests import numpy as np import torch from PIL import Image from io import BytesIO # 替换为raw资源的根路径 loc = 'https://raw.githubusercontent.com/AlexSwiderski/Images/main/pnt/' fname1 = 'ambulance_resized.png' response = requests.get(loc + fname1) # 可选添加请求成功校验 if response.status_code == 200: image = Image.open(BytesIO(response.content)).resize((256, 256)) data = torch.from_numpy(np.asarray(image)[:, :, :3]) / 255. else: print(f"图片请求失败,状态码:{response.status_code}")
额外说明
如果后续需要批量下载该路径下的所有线稿图片,也可以直接将根路径替换为上述raw地址后拼接对应文件名即可,无需再使用GitHub网页路径。
内容的提问来源于stack exchange,提问作者Aswiderski
相关产品推荐
相关产品推荐

