Search code examples
pythongoogle-colaboratory

Change reading path from url to local file in Python


I tried the style transfer from https://www.tensorflow.org/hub/tutorials/tf2_arbitrary_image_stylization on Google colab and i would like to read a local path from Google colab like '/content/a.jpg' instead of a url from other website what should i modify the code?


Solution

  • Try this

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

    You can use your Google drive directory as an external drive.

    Then lets say there is a file called a.jpg in your google drive main folder, you can point to it like this,

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

    if it is in a picture directory withing your drive, you can try this

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

    Then change the load_image function, to this,

    @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
    

    Then you can try,

    load_image(data_dir)