You need to enable JavaScript to run this app. Python中如何将Google Colab图像读取路径从URL修改为本地文件
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何将Google Colab图像读取路径从URL修改为本地文件

TensorFlow风格迁移教程读取Colab本地图片修改方案

核心修改点

  • 移除原教程中通过URL下载图片的tf.keras.utils.get_file相关逻辑,直接指定本地图片路径即可
  • 原教程的图像加载、预处理、模型推理逻辑无需改动,只需要将传入的图片路径替换为Colab本地路径,比如/content/a.jpg

示例修改代码

1. 可选:手动上传图片到Colab运行时

如果还没有上传图片到Colab的/content目录,可以运行以下代码唤起上传窗口:

from google.colab import files
# 运行后选择本地的内容图、风格图上传即可,上传后文件默认保存在/content目录下
uploaded = files.upload()

2. 修改图片路径指定逻辑

将原教程中下载图片的代码替换为路径直接赋值即可,后续的图像加载、预处理、推理代码完全复用原有逻辑:

# 替换为你自己的内容图、风格图本地路径
content_image_path = '/content/你的内容图文件名.jpg'
style_image_path = '/content/你的风格图文件名.jpg'

# 以下为原教程原有逻辑,无需修改
def load_image(path_to_img):
  max_dim = 512
  img = tf.io.read_file(path_to_img)
  img = tf.image.decode_image(img, channels=3)
  img = tf.image.convert_image_dtype(img, tf.float32)

  shape = tf.cast(tf.shape(img)[:-1], tf.float32)
  long_dim = max(shape)
  scale = max_dim / long_dim

  new_shape = tf.cast(shape * scale, tf.int32)

  img = tf.image.resize(img, new_shape)
  img = img[tf.newaxis, :]
  return img

content_image = load_image(content_image_path)
style_image = load_image(style_image_path)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 11:27:01