Broadcasting is a feature of numpy that lets us combine arrays of different sizes.
import numpy as np
a = np.arange(12).reshape(4, 3)*100
print(a)
print(a +1)
a[:2, :2] = 0
print(a)
Example
a = np.arange(12).reshape(4, 3)*100
print(a)
b = np.array([1, 2, 3])
print(b)
print(a+b)
Example
a = np.arange(12).reshape(4, 3)*100
print(a)
b = np.array([1, 2, 3])
print(b)
a.shape
b.shape
Example
c = np.array([1, 2, 3, 4])
a.shape
c.shape
a+c
d = c.reshape(4, 1)
print(d)
print(a)
print(a+d)
Example
import matplotlib.pyplot as plt
a = np.zeros((10, 10, 3))
plt.imshow(a)
plt.show()
a[2:4, :, :].shape
r = np.array([1,0,0])
r.shape
a[2:4, :, :] = r
plt.imshow(a)
plt.axis('off')
plt.show()
a = np.zeros((10, 10, 3))
plt.imshow(a)
plt.show()
colors = np.random.rand(10, 3)
a.shape
plt.imshow(a+colors)
plt.show()
colors2 = colors.reshape(10, 1, 3)
a.shape
plt.imshow(a+colors2)
plt.show()
A boolean array is an array with True/False values. Such arrays can obtained by applying a logical operator some other numpy array:
a = np.array([True, False, False])
print(a)
a = np.arange(16).reshape(4, 4)
print(a)
b = (a>12)
print(b)
c = (a==12)
print(c)
d = (a%3==0)
print(d)
print(a)
Logical operators for combining n=boolean arrays:
~
is the negation&
is the logical "and"|
is the logical "or"print(a)
e = ~(a%3==0)
print(e)
f = (a%2==0) & (a>6)
print(f)
print(a)
b = (a%2 == 0)
print(b)
If a
is a numpy array and b
is a boolean numpy array of the same shape, then a[b]
selects the entries of a
for which the corresponding entry of b
is True
:
c= a[b]
print(c)
a[b] = 100
print(a)
a = np.random.rand(5, 5)
b = np.random.rand(5, 5)
print(a)
print(b)
a[a>b] = 0
print(a)
The imread()
function can be used to read an image file and convert it into a numpy array:
import numpy as np
import matplotlib.pyplot as plt
tiger = plt.imread('tiger.jpg')
print(tiger)
tiger.shape
tiger = tiger/255
print(tiger)
plt.figure(figsize=(10,10))
plt.imshow(tiger)
plt.show()
head = tiger[25:275, 100:375, :]
plt.figure(figsize=(10,10))
plt.imshow(head)
plt.show()
head[:, :, 1] = 0
head[:, :, 2] = 0
plt.figure(figsize=(10,10))
plt.imshow(head)
plt.show()
plt.figure(figsize=(10,10))
plt.imshow(tiger)
plt.show()
tiger[:, 500:550, :] = [0,1,0]
plt.figure(figsize=(10,10))
plt.imshow(tiger)
plt.show()
face = plt.imread('face.png')
print(face)
face.shape
plt.figure(figsize=(10,10))
plt.imshow(face)
plt.show()
face0 = face[:, :, 0]
face0.shape
plt.figure(figsize=(10,10))
plt.imshow(face0, cmap='gray')
plt.show()
np.mean()
and np.median()
¶a = np.random.rand(3,3)
print(a)
np.mean(a)
np.median(a)