在Python中将读取路径从url更改为本地文件



我尝试了谷歌colab上https://www.tensorflow.org/hub/tutorials/tf2_arbitrary_image_stylization的风格转移,我想从谷歌colab上读取本地路径,如'/content/a.p jpg',而不是从其他网站的url,我应该如何修改代码?

试试这个

from google.colab import drive
drive.mount('/content/drive')

你可以使用你的Google驱动器目录作为外部驱动器。

然后假设在你的google drive主文件夹中有一个名为。jpg的文件,你可以像这样指向它,

data_dir  = '/content/drive/MyDrive/a.jpg'

如果它在您的驱动器的图片目录中,您可以尝试这个

data_dir = '/content/drive/MyDrive/pictures/a.jpg'

然后将load_image函数更改为:

@functools.lru_cache(maxsize=None)
def load_image(image_path, image_size=(256, 256), preserve_aspect_ratio=True):
"""Loads and preprocesses images."""
# Load and convert to float32 numpy array, add batch dimension, and normalize to range [0, 1].
img = tf.io.decode_image(
tf.io.read_file(image_path),
channels=3, dtype=tf.float32)[tf.newaxis, ...]
img = crop_center(img)
img = tf.image.resize(img, image_size, preserve_aspect_ratio=True)
return img

那么你可以试试

load_image(data_dir)

最新更新