You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google Colab中从URL读取并批量显示图片?

解决Google Colab中多张图片无法逐一显示的问题

问题原因

Google Colab的代码单元格默认只会自动渲染最后一个单独的表达式输出,同时如果单元格中存在print这类输出语句,会干扰图片的自动渲染逻辑,导致图片无法显示。

解决方案

导入IPython的display模块,主动调用display()函数来显示每张图片,这种方式不受代码顺序或其他输出语句影响。

修改后的代码

!pip install pillow
import urllib.request
from PIL import Image
from IPython.display import display

# 第一张图片
imageURL1 = "https://www.example.com/dir/imagefile1.jpg"
imageName1="file1.jpg"
urllib.request.urlretrieve(imageURL1, imageName1)
img1 = Image.open(imageName1)
display(img1)

# 第二张图片
imageURL2 = "https://www.example.com/dir/imagefile2.jpg"
imageName2="file2.jpg"
urllib.request.urlretrieve(imageURL2, imageName2)
img2 = Image.open(imageName2)
display(img2)

# 现在添加print语句也不会影响图片显示
print("图片加载完成")

说明

  • 通过display()函数可以主动触发每张图片的渲染,每个调用都会生成独立的图片输出。
  • 原代码中直接写img1、img2的方式,仅当该语句是单元格最后一行时才会被自动渲染,且后续的print语句会破坏这种自动渲染机制。

内容的提问来源于stack exchange,提问作者Jim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 02:23:11