import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import random
import time
from imageio import imread
from scipy.misc import imresize
%matplotlib inline
A 1-d array. That's the same as a list.
np.array([5, 4, 10])
array([ 5, 4, 10])
We can access elements of the array as follows:
a = np.array([5, 4, 10])
a[1]
4
The shape of the array is
a.shape
(3,)
Let's now define a 2-d array. You can think of it as a matrix.
a = np.array([[4,5,6], [1,2,3]])
a
array([[4, 5, 6], [1, 2, 3]])
Note that we defined the 2-D array by defining a list of lists, where each of the inner lists was a row.
a.shape # 2 rows, 3 columns
(2, 3)
Accessing elements of the 2-d array:
a[1, 2]
3
a[:, 2] # just column 2
array([6, 3])
a[1, :] # row 1
array([1, 2, 3])
Let's now read in an image
im = imread("prez.jpg")
im
Image([[[242, 235, 217], [242, 235, 217], [242, 235, 217], ..., [146, 133, 117], [147, 134, 118], [147, 134, 118]], [[242, 235, 217], [242, 235, 217], [242, 235, 217], ..., [147, 134, 118], [147, 134, 118], [148, 135, 119]], [[242, 235, 217], [242, 235, 217], [242, 235, 217], ..., [147, 134, 118], [147, 134, 118], [148, 135, 119]], ..., [[200, 188, 174], [198, 189, 174], [198, 189, 174], ..., [ 19, 18, 23], [ 19, 18, 23], [ 17, 16, 21]], [[199, 187, 173], [197, 188, 173], [197, 188, 173], ..., [ 22, 21, 26], [ 22, 21, 26], [ 19, 18, 23]], [[199, 187, 173], [197, 188, 173], [197, 188, 173], ..., [ 22, 21, 26], [ 22, 21, 26], [ 19, 18, 23]]], dtype=uint8)
plt.imshow(im)
<matplotlib.image.AxesImage at 0x7f747e6db2b0>
plt.imshow(im[:, :, 0], cmap = plt.cm.gray)
<matplotlib.image.AxesImage at 0x7f747ce05828>
plt.imshow(im[:, :, 1], cmap = plt.cm.gray)
<matplotlib.image.AxesImage at 0x7f747cd7c128>
plt.imshow(im[:, :, 2], cmap = plt.cm.gray)
<matplotlib.image.AxesImage at 0x7f747cd630b8>
im.shape
(682, 588, 3)
The pixel at (200, 200):
im[200, 200, :]
Image([228, 163, 121], dtype=uint8)
Let's display the image with the red channel zeroed-out
z = np.zeros(im.shape).astype(np.uint8)
z[:, :, 1] = im[:, :, 1]
z[:, :, 2] = im[:, :, 2]
plt.imshow(z)
<matplotlib.image.AxesImage at 0x7f747ccc9128>
Let's convert the image to the range 0..1
im = im/255.0
plt.imshow(im)
<matplotlib.image.AxesImage at 0x7f747cc30198>
Let's now try to display a brigher version of the image
plt.imshow(im * 1.2)
<matplotlib.image.AxesImage at 0x7f747cc19160>
This didn't work because we have values above 1 there.
plt.imshow(np.minimum(im * 1.2, 1))
<matplotlib.image.AxesImage at 0x7f747cb7b5f8>
We can use NumPy for matrix multiplication
M = np.array([[1, 2], [3, 4]])
v = np.array([2, 3])
M
array([[1, 2], [3, 4]])
v
array([2, 3])
np.matmul(M, v)
array([ 8, 18])
M1 = np.array([[1, 2], [3, 4]])
M2 = np.array([[0, 1], [0, 10]])
M1 + M2
array([[ 1, 3], [ 3, 14]])