
PyTorch to Numpy
data = data.to('cpu').detach().numpy().copy()
data = data.detach().numpy().copy()
The method “detach()” is going to create a new torch.Tensor on the same device where the original tensor is located. And also, it will be separated from the computational graph, so the value “requires_grad” equals “False”.
Numpy to PIL
from PIL import Image
image_pil = Image.fromarray(image_np)
PIL to Numpy
import numpy
image_np = numpy.array(image_pil)