Handy Python Snippets

1. Converting between NumPy arrays, PyTorch tensors, and images

NumPy array and PIL image

from PIL import Image  
import numpy as np
im = Image.open("a.jpg")

img = np.array(im) # image to numpy array
im=Image.fromarray(img) # numpy array to image

NumPy array and PyTorch tensor

import torch
import numpy as np
a = torch.ones(5)
b = a.numpy() # torch tensor to numpy array
a = torch.from_numpy(b) # numpy array to torch tensor
# The tensor and array share storage in this example. Mutating either changes the other.

PyTorch tensor and PIL image

from PIL import Image
import torch
import torchvision.transforms as transforms

path_img = "./1.bmp"
img_pil = Image.open(path_img).convert('RGB')
img_tensor = transforms.Compose([
# transforms.Resize((224, 224)),
transforms.ToTensor(), # Image to torch tensor
# transforms.Normalize(norm_mean, norm_std),
])(img_pil)

img = transforms.ToPILImage()(img_tensor)
# torch tensor to Image

2. Converting between NumPy arrays and lists

import numpy as np
a = [[1.0, 2.0], [2.0, 1.0]] # list a
b = np.asarray(a) # list to numpy array
c = b.tolist() # numpy array to list

How arrays and lists differ

A NumPy array has one dtype. A Python list can hold objects of different types.

import numpy as np
a = ['a','b','c','1','2','3']
b = np.array([1,2,3,4,5,6])

3. NumPy sum()

With no axis argument, sum() returns the sum of all elements.

axis selects the dimension to reduce.

For a three-dimensional array, axes 0, 1, and 2 count from the outermost dimension to the innermost.

Negative axes count from the end. In a three-dimensional array, -1 is innermost, and -3 is outermost.

The figure illustrates NumPy sum() along different axes.

image 1

keepdims retains reduced axes as dimensions of length one.

array([[1],[2]])
array([1,2])

4. np.linalg.norm()

linalg stands for linear algebra.

Norm

import numpy as np
x_norm = np.linalg.norm(x, ord=None, axis=None, Keepdims=False)

x is the input vector or matrix.

ord selects the type of norm.

ord Norm type Formula
None L2 norm (default for a vector) $\sqrt{x_1^2+x_2^2+…+x_n^2}$
1 L1 norm $|x_1|+|x_2|+…+|x_n|$
2 L2 norm $\sqrt{x_1^2+x_2^2+…+x_2^2}$
np.inf Infinity norm $max(|x_i|)$

axis determines the dimension or dimensions over which the norm is evaluated.

keepdims retains reduced axes as dimensions of length one.