Numpy¶
Basic Numpy¶
import numpy as np
Create array¶
# empty array np.empty(<shape>)
np.empty((3,2))
array([[4.64967835e-310, 0.00000000e+000],
[0.00000000e+000, 0.00000000e+000],
[0.00000000e+000, 0.00000000e+000]])
# np.linspace(start, stop, len)
# similar to R: seq(from, to, by)
print(
np.linspace(1, 5, 5),
np.linspace(1, 5, 3),
sep = '\n')
[1. 2. 3. 4. 5.]
[1. 3. 5.]
# np.arange(start, stop, step)
# equivalent to R: seq(from, to, by)
print(
np.arange(5), # stop
np.arange(1, 5), # start, stop
np.arange(1, 6, 2), # start, stop, step
sep = '\n'
)
[0 1 2 3 4]
[1 2 3 4]
[1 3 5]
# random array
print(
np.random.rand(),
np.random.rand(3, 5),
np.random.rand(3, 5, 1),
sep = '\n\n'
)
0.1243342257052763
[[0.37067402 0.52523751 0.64556949 0.20251635 0.31186591]
[0.76393491 0.71054838 0.38912143 0.41679623 0.58198636]
[0.2743352 0.02532827 0.82378454 0.84843088 0.3390712 ]]
[[[0.98378478]
[0.29438406]
[0.23131775]
[0.84617288]
[0.38511699]]
[[0.13675279]
[0.75574176]
[0.15372809]
[0.73705805]
[0.73187824]]
[[0.10777166]
[0.34323938]
[0.66599043]
[0.58093256]
[0.27132764]]]
# create array from tuple or list
a = np.array([(1,2,3),
(4,5,6)],
dtype = float)
print(a)
print(type(a), type(a[0,0]))
[[1. 2. 3.]
[4. 5. 6.]]
<class 'numpy.ndarray'> <class 'numpy.float64'>
Changing Shape¶
print(a.shape)
a.shape = (3, 2)
print(a.shape)
a
(2, 3)
(3, 2)
array([[1., 2.],
[3., 4.],
[5., 6.]])
Common Functions¶
Arithmetic¶
a = np.array([1,2,3], dtype=float)
b = np.array([4,5,6], dtype=float)
print(
a + b,
a / b,
a * 3,
a.dot(b), # dot product
a @ b, # dot product
np.sin(a),
sep = '\n\n')
[5. 7. 9.]
[0.25 0.4 0.5 ]
[3. 6. 9.]
32.0
32.0
[0.84147098 0.90929743 0.14112001]
Logarithm & Exponential¶
Numpy doesn’t have log function for arbitrary base, so use the rule: \(log_b a = \frac{log_x a}{log_x b}\).
# log with base 2
np.isclose(
np.log2(a), np.log(a)/np.log(2)
)
array([ True, True, True])
print(
np.e,
np.exp([0, 1, 2]),
np.isclose(np.e, np.exp(1)),
sep = '\n'
)
2.718281828459045
[1. 2.71828183 7.3890561 ]
True
Aggregate Functions¶
a = np.array([(1,2,3),
(4,5,6)])
print(
a.shape,
a.sum(), # all elements
a.sum(axis=0), # column wise
a.sum(axis=1), # row wise
sep='\n'
)
(2, 3)
21
[5 7 9]
[ 6 15]
print(
np.median(a),
np.median(a, axis=0),
np.cumsum(a),
sep = '\n'
)
3.5
[2.5 3.5 4.5]
[ 1 3 6 10 15 21]
Modify Array¶
a = np.array([1, 2, 3, 1, 4])
idx, = np.where(a == 1) # np.where returns a tuple when only condition provided
print(idx)
a = np.delete(a, idx)
a
[0 3]
array([2, 3, 4])
a = np.array([1, 2, 3, 1, 4])
idx = np.where(a == 1, True, False)
print(idx)
b = a[~idx]
b
[ True False False True False]
array([2, 3, 4])
Image processing with matplotlib & numpy¶
%matplotlib inline
from matplotlib.image import imread
import matplotlib.pyplot as plt
img = imread('/home/liao/img/bg/road-straight.jpg')
plt.imshow(img)
<matplotlib.image.AxesImage at 0x7feae949bf10>
img.shape
(1280, 1920, 3)
img[::, ::, ::] == img
array([[[ True, True, True],
[ True, True, True],
[ True, True, True],
...,
[ True, True, True],
[ True, True, True],
[ True, True, True]],
[[ True, True, True],
[ True, True, True],
[ True, True, True],
...,
[ True, True, True],
[ True, True, True],
[ True, True, True]],
[[ True, True, True],
[ True, True, True],
[ True, True, True],
...,
[ True, True, True],
[ True, True, True],
[ True, True, True]],
...,
[[ True, True, True],
[ True, True, True],
[ True, True, True],
...,
[ True, True, True],
[ True, True, True],
[ True, True, True]],
[[ True, True, True],
[ True, True, True],
[ True, True, True],
...,
[ True, True, True],
[ True, True, True],
[ True, True, True]],
[[ True, True, True],
[ True, True, True],
[ True, True, True],
...,
[ True, True, True],
[ True, True, True],
[ True, True, True]]])
Modify Image: Compression¶
Compress image by cutting the resolution to half, i.e. subset every two rows and every two columns in ndarray.
plt.imshow(img[::2, ::2, :])
<matplotlib.image.AxesImage at 0x7feae7c1db50>
Modify Image: Color Mask¶
# np.where(<cond>, <value for True>, <value for False>)
img_mask = np.where(img > 180, 255, img)
plt.imshow(img_mask)
<matplotlib.image.AxesImage at 0x7feae7b8ecd0>
# np.where(<cond>, <value for True>, <value for False>)
img_mask = np.where(img < 80, 0, img)
plt.imshow(img_mask)
<matplotlib.image.AxesImage at 0x7feae7b01b10>