# AUTOGENERATED! DO NOT EDIT! File to edit: ../01_PyTorch_Basics.ipynb.

# %% auto 0
__all__ = ['load_image_pil', 'pil_from_url', 'pil_to_tensor', 'tensor_to_pil']

# %% ../01_PyTorch_Basics.ipynb 4
import torch
import torchvision
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image

# %% ../01_PyTorch_Basics.ipynb 47
def load_image_pil(fn, size=None):
    im = Image.open(fn).convert('RGB')
    if size != None:
        im = im.resize(size)
    return im

# %% ../01_PyTorch_Basics.ipynb 51
import requests
from io import BytesIO

def pil_from_url(url, size=None):
    response = requests.get(url)
    im = Image.open(BytesIO(response.content)).convert('RGB')
    if size != None:
        im = im.resize(size)
    return im

# %% ../01_PyTorch_Basics.ipynb 59
def pil_to_tensor(im):
    # TODO split into multiple lines and explain
    return torch.tensor(np.array(im)).permute(2, 0, 1).unsqueeze(0)/255.0

def tensor_to_pil(tensor_im):
    tensor_im = tensor_im.squeeze() # In case there is a batch dimension
    tensor_im = tensor_im.detach().cpu() # Detach from computational graph - explained in next lesson!
    tensor_im = tensor_im.permute(1, 2, 0) # Rearrange the channels
    tensor_im = tensor_im.clip(0, 1)*255 # Note that we clip to (0, 1) before scaling to (0, 255)
    im_array = np.array(tensor_im).astype(np.uint8) # Convert to int as required by PIL
    im = Image.fromarray(im_array) # Convert to PIL image
    return im
