如何使用PyScript结合Matplotlib从GitHub加载并显示图片?
PyScript加载GitHub图片并使用Matplotlib显示的问题解决
问题描述
使用PyScript从GitHub加载CSV数据的示例可正常运行:
url = ( "https://raw.githubusercontent.com/Cheukting/pyscript-ice-cream/main/bj-products.csv" ) ice_data = pd.read_csv(open_url(url))
但尝试加载GitHub上的JPG图片并通过Matplotlib显示时,代码无法正常运行:
from pyodide.http import open_url import matplotlib.pyplot as plt from PIL import Image fig, ax = plt.subplots(figsize=(15, 15)) image = Image.open(open_url("https://raw.githubusercontent.com/path/to/img.jpg")) ax.imshow(image) display(fig, target="graph-area", append=False)
解决方案
问题出在open_url的返回值处理上:open_url返回的是HTTP响应对象,无法直接被Image.open识别。需要先读取响应的字节数据,再用BytesIO包装成PIL可处理的流对象。修正后的代码如下:
from pyodide.http import open_url import matplotlib.pyplot as plt from PIL import Image from io import BytesIO fig, ax = plt.subplots(figsize=(15, 15)) # 读取图片字节并转换为BytesIO流 image_bytes = open_url("https://raw.githubusercontent.com/path/to/img.jpg").read() image = Image.open(BytesIO(image_bytes)) ax.imshow(image) # 可选:隐藏坐标轴让图片显示更整洁 ax.axis('off') display(fig, target="graph-area", append=False)
关键说明
open_url()返回的是HTTP响应类对象,直接传给Image.open()会导致PIL无法解析,必须先调用.read()获取字节数据。- 用
BytesIO将字节数据包装成类文件对象,才能符合Image.open()的输入要求。 - 确保替换代码中的图片URL为GitHub仓库里的原始图片链接(不是网页预览链接,需确认链接以
raw.githubusercontent.com开头)。
内容的提问来源于stack exchange,提问作者Justin Essert
相关产品推荐
相关产品推荐

