None of the code below will work without this!
import numpy as np
np.__version__
# all zeros, specified shape
np.zeros( (2,3) )
# all ones, specified shape
np.ones( (8,) )
# array with every entry equal to a given constant
np.full( (3,3), 1.7 ) # shape, value
A = np.ones( (4,4) )
A.ndim # the dimension of A
A.shape # the shape of A
A.size # the number of elements in A
A.dtype # the data type (np.ones gives float64 by default)
B = np.full( (2,3), 6 ) # Python int given, converted to int64
B.dtype
# Build array from an iterable
C = np.array( [[5,6,7,8],[9,10,11,12]] )
print(C.ndim)
print(C.dtype)
print(C.size)
# np.random.random(shape) gives array of uniformly distributed
# random floats 0<=x<1
np.random.random((5,8))
np.ones((2,2),dtype="bool") # numpy supports boolean arrays
# coerces 0 to False and 1 to True
Abyte = np.zeros((4,3),dtype="uint8") # Array of 1-byte values
Abyte
Abyte[1,1] = 10
Abyte[3,2] = 300
Abyte
np.arange
is start, stop, stepnp.linspace
is first, last, nstepnp.arange(3,13,2) # stop will not be included
np.arange(3,5,0.1)
np.linspace(2,6,4)
A = np.array(range(24)).reshape((4,6)) # 0..23 in a vector, but then convert to 4x6 matrix
v = np.arange(1,5,1.2) # vector (array with ndim=1)
A
v
v[1] # element at index 1 (zero-based)
v[-2] # second to last element
A[2,0] # row 2, column 0
A[:,2] # column 2 of A (remember, 0-based numbering!)
# I think of this as A[anything,2]
A[1,:] # row 1 of A
# I think of this as A[1,anything]
A[1] # another way to specify row 1 of A
# missing indices are treated as ":"
A[::2,1:3] # all rows of even index, columns 1 and 2
Vectors are 1D arrays
v = np.array([1.5,2.5,1])
v
w = np.array([-0.5,3,0])
w
2.1*v # elementwise multiplication
v+w
v*w # There's a good chance this isn't what you want.
v.dot(w)
Matrices are 2D arrays
M = np.eye(3)
M
M[1] = np.linspace(10,20,3)
M
6*M
M.T # transpose reverses the order of the axes; M.T[j,k] is M[k,j]
# Let's make an array to work with
A = np.array(range(1,16)).reshape((3,5))
A
1 / A # reciprocal of each entry in the matrix
A**2 # square of each entry
np.sin(A) # apply sin() to each entry
# first 11 cubes
np.arange(1,12)**3 # make vector of 1..11 and then cube each entry
If a higher-dimensional array is needed for an operation, produce one by duplication.
A = np.full((3,4),5,dtype="float")
A[1] = 11
A
5+A
v = np.array( [1,2,3,4], dtype="float")
v
A + v # add v to each row of A
# 3x4 (3x)4
B = np.zeros( (6,6) )
B[::2,1:5] = 7
B
A = np.arange(1,10).reshape((3,3))
A
B = np.array( [ [10,20,30], [19,23,56]])
B
C = np.array( [ [2,1], [1,1] ])
C
np.vstack([A,A])
np.hstack([A,A])
v = np.arange(15)
v
np.sum(v)
np.max(v)
np.mean(v)
np.all(v) # are all of the elements True / nonzero?
np.any(v) # is there at least one True / nonzero element
Suppose we want to consider a rectangular grid of points in the plane. Numpy has a function to take a list of x values, a list of y values, and then return all possible pairs of x and y from these lists in a convenient form.
x = np.linspace(-1,1,11)
x
y = np.linspace(0,2,6)
y
xx,yy = np.meshgrid(x,y) # will return two len(y) x len(x) arrays
# xx will be constant along columns (values from x along rows)
# yy will be constant along rows (values from y along columns)
xx
yy
# A is the sum of two matrices:
# 4x4 zeros, add [0,1,2,3] to each row, take the transpose
# 4x4 zeros, add [0,2,4,6] to each row
A = (np.zeros((4,4))+np.arange(4)).T + (np.zeros((4,4))+np.arange(0,8,2))
# -3 to 3
v = np.arange(-3,4)
w = np.array([-2,-2,0,0,4,5,5])
A
v
w
v==w
v>w
v<w
A == np.zeros((4,4))
A
mask = np.array( [True, True, False, False, False, True, False])
mask.dtype
v
v[mask] # 1D array of all the entries in v where mask is True
mask2d = np.zeros((4,4),dtype="bool")
mask2d[0,0] = True
mask2d[2,3] = True
mask2d
A[mask2d]
v
mask
v[mask] = 275
v
# -3 to 3
v = np.arange(-3,4)
v
v[mask]+=1
# v[mask] = v[mask] + 1
# ^^^^^^^^^^^ broadcasting
v
v[v<0] = 0
v
A
A[A%2==0] = 42
A
np.any(A<0) # Does A have any entries that are negative?
np.array(img)
just works, if img
is a PIL.Image
objectPIL.Image.fromarray(A)
to make an image from an array(height,width)
and dtype uint8
for grayscale(height,width,3)
and dtype uint8
for color (last axis is red, green, blue)import numpy as np
from PIL import Image
grid_of_zeros = np.zeros( (256,256) )
# Make the red data: more red as you go to the right
r = np.arange(256) + grid_of_zeros # broadcasting makes this 256x256
# Make the green data: more green as you go to the left
g = 255 - np.arange(256) + grid_of_zeros # broadcasting makes this 256x256
# Make the blue data: More blue at the top
b = (255 - np.arange(256) + grid_of_zeros).T
# Stack these three "planes" into an array of size 256x256x3
# Note the `axis=2` is needed so they are stacked with the size-3 dimension
# being the last one. If we omit this you get the same data but as 256x256x3
imgdata = np.stack([r,g,b],axis=2).astype("uint8")
# Make an image out of it
Image.fromarray(imgdata)