Numpy 基礎知識
ndarray數組和list清單分别完成對每個元素增加1的計算
# https://aistudio.baidu.com/aistudio/projectdetail/
# ndarray數組和list清單分别完成對每個元素增加1的計算
# Python原生的list
# 假設有兩個list
a = [1, 2, 3, 4, 5]
b = [2, 3, 4, 5, 6]
# 完成如下計算
# 1 對a的每個元素 + 1
# a = a + 1 不能這麼寫,會報錯
# a[:] = a[:] + 1 也不能這麼寫,也會報錯
for i in range(5):
a[i] = a[i] + 1
a
[2, 3, 4, 5, 6]
# 使用ndarray
import numpy as np
a = np.array([1, 2, 3, 4, 5])
a = a + 1
a
array([2, 3, 4, 5, 6])
# 2 計算 a和b中對應位置元素的和,是否可以這麼寫?
a = [1, 2, 3, 4, 5]
b = [2, 3, 4, 5, 6]
c = a + b
# 檢查輸出發現,不是想要的結果
c
[1, 2, 3, 4, 5, 2, 3, 4, 5, 6]
# 使用for循環,完成兩個list對應位置元素相加
c = []
for i in range(5):
c.append(a[i] + b[i])
c
[3, 5, 7, 9, 11]
# 使用numpy中的ndarray完成兩個ndarray相加
import numpy as np
a = np.array([1, 2, 3, 4, 5])
b = np.array([2, 3, 4, 5, 6])
c = a + b
c
array([ 3, 5, 7, 9, 11])
'''
從上面的示例中可以看出,ndarray數組的矢量計算能力使得不需要寫for循環,
就可以非常友善的完成數學計算,在操作矢量或者矩陣時,可以像操作普通的數值變量一樣編寫程式,
使得代碼極其簡潔。另外,ndarray數組還提供了廣播機制,它會按一定規則自動對數組的次元進行擴充以完成計算,
如下面例子所示,1維數組和2維數組進行相加操作,ndarray數組會自動擴充1維數組的次元,然後再對每個位置的元素分别相加。
'''
# 自動廣播機制,1維數組和2維數組相加
# 二維數組次元 2x5
# array([[ 1, 2, 3, 4, 5],
# [ 6, 7, 8, 9, 10]])
d = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
# c是一維數組,次元5
# array([ 4, 6, 8, 10, 12])
c = np.array([ 4, 6, 8, 10, 12])
e = d + c
e
array([[ 5, 8, 11, 14, 17],
[10, 13, 16, 19, 22]])
建立ndarray數組
'''
有如下幾種方式建立ndarray數組
從list清單建立
指定起止範圍及間隔建立
建立值全為0的ndarray數組
建立值全為1的ndarray數組
'''
# 導入numpy
import numpy as np
# 從list建立array
a = [1,2,3,4,5,6]
b = np.array(a)
b
array([1, 2, 3, 4, 5, 6])
# 通過np.arange建立
# 通過指定start, stop (不包括stop),interval來産生一個1為的ndarray
a = np.arange(0, 20, 2)
a
array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
# 建立全0的ndarray
a = np.zeros([3,3])
a
array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
# 建立全1的ndarray
a = np.ones([3,3])
a
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
# 檢視ndarray數組的屬性
# ndarray的屬性包括形狀shape、資料類型dtype、元素個數size和次元ndim等,下面的程式展示如何檢視這些屬性
# 自定義類型
x = np.ones([3,3], dtype = int)
print(x)
print('a, ndim: {}'.format(a.ndim))
[[1 1 1]
[1 1 1]
[1 1 1]]
a, ndim: 2
# 數組的資料類型 ndarray.dtype
# 數組的形狀 ndarray.shape,1維數組(N, ),二維數組(M, N),三維數組(M, N, K)
# 數組的次元大小,ndarray.ndim, 其大小等于ndarray.shape所包含元素的個數
# 數組中包含的元素個數 ndarray.size,其大小等于各個次元的長度的乘積
a = np.ones([3, 3])
print('a, dtype: {} \t ,shape: {}'.format(a.dtype, a.shape))
print('a, size: {} \t\t ,ndim: {}'.format(a.size, a.ndim))
a, dtype: float64 ,shape: (3, 3)
a, size: 9 ,ndim: 2
# 轉化資料類型
# 原來 a的dtype是float64,現在變成了dtype是int64
b = a.astype(np.int64)
print('b, dtype: {}, shape: {}'.format(b.dtype, b.shape))
# 改變形狀
c = a.reshape([1, 9])
print('c, dtype: {}, shape: {}'.format(c.dtype, c.shape))
b, dtype: int64, shape: (3, 3)
c, dtype: float64, shape: (1, 9)
'''
ndarray數組的基本運算
ndarray數組可以像普通的數值型變量一樣進行加減乘除操作,這一小節将介紹兩種形式的基本運算:
标量和ndarray數組之間的運算
兩個ndarray數組之間的運算
'''
# 标量除以數組,用标量除以數組的每一個元素
arr = np.array([[1., 2., 3.], [4., 5., 6.]])
1. / arr
array([[1. , 0.5 , 0.33333333],
[0.25 , 0.2 , 0.16666667]])
# 标量乘以數組,用标量乘以數組的每一個元素
arr = np.array([[1., 2., 3.], [4., 5., 6.]])
2.0 * arr
array([[ 2., 4., 6.],
[ 8., 10., 12.]])
# 标量加上數組,用标量加上數組的每一個元素
arr = np.array([[1., 2., 3.], [4., 5., 6.]])
2.0 + arr
array([[3., 4., 5.],
[6., 7., 8.]])
# 标量減去數組,用标量減去數組的每一個元素
arr = np.array([[1., 2., 3.], [4., 5., 6.]])
2.0 - arr
array([[ 1., 0., -1.],
[-2., -3., -4.]])
# 數組 減去 數組, 用對應位置的元素相減
arr1 = np.array([[1., 2., 3.], [4., 5., 6.]])
arr2 = np.array([[11., 12., 13.], [21., 22., 23.]])
arr1 - arr2
array([[-10., -10., -10.],
[-17., -17., -17.]])
# 數組 加上 數組, 用對應位置的元素相加
arr1 = np.array([[1., 2., 3.], [4., 5., 6.]])
arr2 = np.array([[11., 12., 13.], [21., 22., 23.]])
arr1 + arr2
array([[12., 14., 16.],
[25., 27., 29.]])
# 數組 乘以 數組,用對應位置的元素相乘
arr1 * arr2
array([[ 11., 24., 39.],
[ 84., 110., 138.]])
# 數組 除以 數組,用對應位置的元素相除
arr1 / arr2
array([[0.09090909, 0.16666667, 0.23076923],
[0.19047619, 0.22727273, 0.26086957]])
# 數組開根号,将每個位置的元素都開根号
# arr = np.array([[1., 2., 3.], [4., 5., 6.]])
arr ** 0.5
array([[1. , 1.41421356, 1.73205081],
[2. , 2.23606798, 2.44948974]])
'''
在程式中,通常需要通路或者修改ndarray數組某個位置的元素,也就是要用到ndarray數組的索引;
有些情況下可能需要通路或者修改一些區域的元素,則需要使用數組的切片。索引和切片的使用方式與Python中的list類似,
ndarray數組可以基于 -n ~ n-1 的下标進行索引,切片對象可以通過内置的 slice 函數,并設定 start, stop 及 step 參數進行,
從原數組中切割出一個新數組。
'''
# 1維數組索引和切片
a = np.arange(30)
a[10]
10
a = np.arange(30)
b = a[4:7]
b
array([4, 5, 6])
#将一個标量值指派給一個切片時,該值會自動傳播到整個選區(如下圖所示)
a = np.arange(30)
a[4:7] = 10
a
array([ 0, 1, 2, 3, 10, 10, 10, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29])
# 數組切片是原始數組的視圖。這意味着資料不會被複制,
# 視圖上的任何修改都會直接反映到源數組上
a = np.arange(30)
arr_slice = a[4:7]
arr_slice[0] = 100
a, arr_slice
(array([ 0, 1, 2, 3, 100, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29]), array([100, 5, 6]))
# 通過copy給新數組建立不同的記憶體空間
a = np.arange(30)
arr_slice = a[4:7]
arr_slice = np.copy(arr_slice)
arr_slice[0] = 100
a, arr_slice
(array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]),
array([100, 5, 6]))
# 多元數組索引和切片
a = np.arange(30)
arr3d = a.reshape(5, 3, 2)
arr3d
array([[[ 0, 1],
[ 2, 3],
[ 4, 5]],
[[ 6, 7],
[ 8, 9],
[10, 11]],
[[12, 13],
[14, 15],
[16, 17]],
[[18, 19],
[20, 21],
[22, 23]],
[[24, 25],
[26, 27],
[28, 29]]])
# 隻有一個索引名額時,會在第0維上索引,後面的次元保持不變
arr3d[0]
array([[0, 1],
[2, 3],
[4, 5]])
# 兩個索引名額
arr3d[0][1]
array([2, 3])
# 兩個索引名額
arr3d[0, 1]
array([2, 3])
# 使用python中的for文法對數組切片
a = np.arange(24)
a
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23])
a = a.reshape([6, 4])
a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]])
# 使用for語句生成list
[k for k in range(0, 6, 2)]
[0, 2, 4]
# 結合上面列出的for語句的用法
# 使用for語句對數組進行切片
# 下面的代碼會生成多個切片構成的list
# k in range(0, 6, 2) 決定了k的取值可以是0, 2, 4
# 産生的list的包含三個切片
# 第一個元素是a[0 : 0+2],
# 第二個元素是a[2 : 2+2],
# 第三個元素是a[4 : 4+2]
slices = [a[k:k+2] for k in range(0, 6, 2)]
slices
[array([[0, 1, 2, 3],
[4, 5, 6, 7]]), array([[ 8, 9, 10, 11],
[12, 13, 14, 15]]), array([[16, 17, 18, 19],
[20, 21, 22, 23]])]
array([[0, 1, 2, 3],
[4, 5, 6, 7]])
ndarray數組的統計運算
# 這一小節将介紹如何計算ndarray數組的各個統計量,包括以下幾項:
'''
mean 均值
std 标準差
var 方差
sum 求和
max 最大值
min 最小值
'''
計算均值
# 計算均值,使用arr.mean() 或 np.mean(arr),二者是等價的
arr = np.array([[1,2,3], [4,5,6], [7,8,9]])
print(arr)
arr.mean(), np.mean(arr)
[[1 2 3]
[4 5 6]
[7 8 9]]
(5.0, 5.0)
求和
# 求和
arr.sum(),np.sum(arr)
(45, 45)
求最大值
# 求最大值
arr.max(), np.max(arr)
(9, 9)
求最小值
# 求最小值
arr.min(), np.min(arr)
(1, 1)
次元
# 指定計算的次元
# 沿着第1維求平均,也就是将[1, 2, 3]取平均等于2,[4, 5, 6]取平均等于5,[7, 8, 9]取平均等于8
arr.mean(axis = 1)
array([2., 5., 8.])
# 沿着第0維求和,也就是将[1, 4, 7]求和等于12,[2, 5, 8]求和等于15,[3, 6, 9]求和等于18
arr.sum(axis=0)
array([12, 15, 18])
# 沿着第0維求最大值,也就是将[1, 4, 7]求最大值等于7,[2, 5, 8]求最大值等于8,[3, 6, 9]求最大值等于9
arr.max(axis=0)
array([7, 8, 9])
# 沿着第1維求最小值,也就是将[1, 2, 3]求最小值等于1,[4, 5, 6]求最小值等于4,[7, 8, 9]求最小值等于7
arr.min(axis=1)
array([1, 4, 7])
'''
标準差是一組資料平均值分散程度的一種度量。
标準差是方差的算術平方根。
标準差公式如下:
std = sqrt(mean((x - x.mean())**2))
如果數組是 [1,2,3,4],則其平均值為 2.5。
是以,差的平方是 [2.25,0.25,0.25,2.25],并且其平均值的平方根除以 4,
即 sqrt(5/4) ,結果為 1.1180339887498949。
'''
#計算步驟
# 第一步計算平均值
# 第二步計算标準差
#方差: ((1-2.5)^2+ (2-2.5)^2+ (3-2.5)^2+ (4-2.5)^2)/4 = 5/4 = 1.25
#标準差: 标準差=方差的算術平方根=sqrt(5/4)=1.1180339887499
# 計算标準差
cc = arr.std()
print(cc,'\n')
# 計算标準差---分步計算
# 第一步
# 矩陣平均值
b = np.mean(arr)
print('矩陣arr平均值,b=',b,'\n')
# 第二步
# arr的所有元素減去平均值,得到一個新矩陣c:
c = arr-b
print(c,'\n')
# c的所有元素各自平方:
d=c**2
print(d)
# d的平均值,就是矩陣a的方差。
e=np.mean(d)
print(e)
#e的二次開方,就是矩陣a的标準差,又叫做均方差。
print(e**0.5)
# 合起來寫
( np.mean((arr - np.mean(arr))**2) )**0.5
2.581988897471611
矩陣arr平均值,b= 5.0
[[-4. -3. -2.]
[-1. 0. 1.]
[ 2. 3. 4.]]
[[16. 9. 4.]
[ 1. 0. 1.]
[ 4. 9. 16.]]
6.666666666666667
2.581988897471611
2.581988897471611
# 計算方差
arr.var()
6.666666666666667
# 找出最大元素的索引
arr.argmax(), arr.argmax(axis=0), arr.argmax(axis=1)
(8, array([2, 2, 2]), array([2, 2, 2]))
# 找出最小元素的索引
arr.argmin(), arr.argmin(axis=0), arr.argmin(axis=1)
(0, array([0, 0, 0]), array([0, 0, 0]))
# 随機數np.random
'''
建立随機ndarray數組
設定随機數種子
随機打亂順序
随機選取元素
'''
# 生成均勻分布随機數,随機數取值範圍在[0, 1)之間
a = np.random.rand(3, 3)
a
array([[0.45394656, 0.43636125, 0.38469212],
[0.75350958, 0.51052504, 0.26435309],
[0.90073186, 0.2131814 , 0.30692401]])
# 生成均勻分布随機數,指定随機數取值範圍和數組形狀
a = np.random.uniform(low = -1.0, high = 1.0, size=(2,2))
a
array([[-0.70902069, -0.69851606],
[ 0.63063448, 0.06905212]])
# 生成标準正态分布随機數
a = np.random.randn(3, 3)
a
array([[ 0.44343123, -0.67650976, 2.00080694],
[ 1.6800222 , 0.11371525, -1.10454078],
[-1.20857614, -0.10291411, -0.60176336]])
# 生成正态分布随機數,指定均值loc和方差scale
'''
loc:float
此機率分布的均值(對應着整個分布的中心centre)
scale:float
此機率分布的标準差(對應于分布的寬度,scale越大越矮胖,scale越小,越瘦高)
size:int or tuple of ints
輸出的shape,預設為None,隻輸出一個值
'''
a = np.random.normal(loc = 1.0, scale = 1.0, size = (3,3))
a
array([[2.2616859 , 1.41765968, 1.89395769],
[1.04735517, 0.39157448, 0.73145187],
[0.33369803, 0.65598817, 1.80705192]])
# 可以多次運作,觀察程式輸出結果是否一緻
# 如果不設定随機數種子,觀察多次運作輸出結果是否一緻
np.random.seed(10)
a = np.random.rand(3, 3)
a
array([[0.77132064, 0.02075195, 0.63364823],
[0.74880388, 0.49850701, 0.22479665],
[0.19806286, 0.76053071, 0.16911084]])
# 生成一維數組
a = np.arange(0, 30)
# 打亂一維數組順序
print('before random shuffle: ', a)
np.random.shuffle(a)
print('after random shuffle: ', a)
before random shuffle: [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
24 25 26 27 28 29]
after random shuffle: [10 21 26 7 0 23 2 17 18 20 12 6 9 3 25 5 13 14 24 29 1 28 11 15
27 16 19 4 22 8]
# 生成一維數組
a = np.arange(0, 30)
# 将一維數組轉化成2維數組
a = a.reshape(10, 3)
# 打亂一維數組順序
print('before random shuffle: \n{}'.format(a))
np.random.shuffle(a)
print('after random shuffle: \n{}'.format(a))
before random shuffle:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]
[12 13 14]
[15 16 17]
[18 19 20]
[21 22 23]
[24 25 26]
[27 28 29]]
after random shuffle:
[[15 16 17]
[12 13 14]
[27 28 29]
[ 3 4 5]
[ 9 10 11]
[21 22 23]
[18 19 20]
[ 0 1 2]
[ 6 7 8]
[24 25 26]]
随機打亂1維數組順序時,發現所有元素位置都改變了;随機打亂二維數組順序時,發現隻有第行的順序被打亂了,列的順序保持不變。
# 随機選取一選部分元素
a = np.arange(30)
b = np.random.choice(a, size=5)
b
array([11, 28, 1, 20, 26])
# 線性代數
'''
Numpy中實作了線性代數中常用的各種操作,并形成了numpy.linalg線性代數相關的子產品。其中包括:
diag 以一維數組的形式傳回方陣的對角線(或非對角線)元素,或将一維數組轉換為方陣(非對角線元素為0)
dot 矩陣乘法
trace 計算對角線元素的和
det 計算矩陣行列式
eig 計算方陣的特征值和特征向量
inv 計算方陣的逆
感興趣的讀者可以檢視各個操作相關的文檔,或者np.linalg的文檔以了解更多操作。
'''
# 矩陣相乘
a = np.arange(12)
b = a.reshape([3, 4])
c = a.reshape([4, 3])
# 矩陣b的第二維大小,必須等于矩陣c的第一維大小
d = b.dot(c) # 等價于 np.dot(b, c)
print('a: \n{}'.format(a))
print('b: \n{}'.format(b))
print('c: \n{}'.format(c))
print('d: \n{}'.format(d))
a:
[ 0 1 2 3 4 5 6 7 8 9 10 11]
b:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
c:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
d:
[[ 42 48 54]
[114 136 158]
[186 224 262]]
# numpy.linalg 中有一組标準的矩陣分解運算以及諸如求逆和行列式之類的東西
# np.linalg.diag 以一維數組的形式傳回方陣的對角線(或非對角線)元素,
# 或将一維數組轉換為方陣(非對角線元素為0)
e = np.diag(d)
f = np.diag(e)
print('d: \n{}'.format(d))
print('e: \n{}'.format(e))
print('f: \n{}'.format(f))
d:
[[ 42 48 54]
[114 136 158]
[186 224 262]]
e:
[ 42 136 262]
f:
[[ 42 0 0]
[ 0 136 0]
[ 0 0 262]]
NumPy 提供了線性代數函數庫 linalg,該庫包含了線性代數所需的所有功能,可以看看下面的說明:
函數 | 描述 |
---|---|
| 兩個數組的點積,即元素對應相乘。 |
| 兩個向量的點積 |
| 兩個數組的内積 |
| 兩個數組的矩陣積 |
| 數組的行列式 |
| 求解線性矩陣方程 |
| 計算矩陣的乘法逆矩陣 |
# trace, 計算對角線元素的和
g = np.trace(d)
g
440
# det,計算行列式
h = np.linalg.det(d)
h
# 1.3642420526593978e-11
0.0
# eig,計算特征值和特征向量
i = np.linalg.eig(d)
i
(array([ 4.36702561e+02, 3.29743887e+00, -2.00728619e-14]),
array([[ 0.17716392, 0.77712552, 0.40824829],
[ 0.5095763 , 0.07620532, -0.81649658],
[ 0.84198868, -0.62471488, 0.40824829]]))
# inv,計算方陣的逆
tmp = np.random.rand(3, 3)
j = np.linalg.inv(tmp)
j
array([[ 1.18679461, -2.90322073, 1.76460933],
[ 6.0206646 , -7.15058371, 1.40335906],
[-4.54552928, 7.07527466, -1.58788599]])
# Numpy儲存和導入檔案
# Numpy還可以友善的進行檔案讀寫,比如對于下面這種格式的文本檔案:
# 使用np.fromfile從文本檔案'housing.data'讀入資料
# 這裡要設定參數sep = ' ',表示使用空白字元來分隔資料
# 空格或者回車都屬于空白字元,讀入的資料被轉化成1維數組
d = np.fromfile('./work/housing.data', sep = ' ')
d
# 産生随機數組a
a = np.random.rand(3,3)
np.save('a.npy', a)
# 從磁盤檔案'a.npy'讀入數組
b = np.load('a.npy')
# 檢查a和b的數值是否一樣
check = (a == b).all()
check
下面使用numpy和matplotlib計算函數值并畫出圖形
# 下面使用numpy和matplotlib計算函數值并畫出圖形
# ReLU和Sigmoid激活函數示意圖
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.patches as patches
#設定圖檔大小
plt.figure(figsize=(8, 3))
# x是1維數組,數組大小是從-10. 到10.的實數,每隔0.1取一個點
x = np.arange(-10, 10, 0.1)
# 計算 Sigmoid函數
s = 1.0 / (1 + np.exp(- x))
# 計算ReLU函數
y = np.clip(x, a_min = 0., a_max = None)
#########################################################
# 以下部分為畫圖程式
# 設定兩個子圖視窗,将Sigmoid的函數圖像畫在左邊
f = plt.subplot(121)
# 畫出函數曲線
plt.plot(x, s, color='r')
# 添加文字說明
plt.text(-5., 0.9, r'$y=\sigma(x)$', fontsize=13)
# 設定坐标軸格式
currentAxis=plt.gca()
currentAxis.xaxis.set_label_text('x', fontsize=15)
currentAxis.yaxis.set_label_text('y', fontsize=15)
# 将ReLU的函數圖像畫在左邊
f = plt.subplot(122)
# 畫出函數曲線
plt.plot(x, y, color='g')
# 添加文字說明
plt.text(-3.0, 9, r'$y=ReLU(x)$', fontsize=13)
# 設定坐标軸格式
currentAxis=plt.gca()
currentAxis.xaxis.set_label_text('x', fontsize=15)
currentAxis.yaxis.set_label_text('y', fontsize=15)
plt.show()

Numpy應用舉例——圖像翻轉和裁剪
# 導入需要的包
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
# 讀入圖檔
image = Image.open('./work/000000001584.jpg')
image = np.array(image)
# 檢視資料形狀,其形狀是[H, W, 3],
# 其中H代表高度, W是寬度,3代表RGB三個通道
image.shape
(612, 612, 3)
# 原始圖檔
plt.imshow(image)
<matplotlib.image.AxesImage at 0x7f8df70d6978>
# 垂直方向翻轉
# 這裡使用數組切片的方式來完成,
# 相當于将圖檔最後一行挪到第一行,
# 倒數第二行挪到第二行,...,
# 第一行挪到倒數第一行
# 對于行名額,使用::-1來表示切片,
# 負數步長表示以最後一個元素為起點,向左走尋找下一個點
# 對于列名額和RGB通道,僅使用:表示該次元不改變
image2 = image[::-1, :, :]
plt.imshow(image2)
<matplotlib.image.AxesImage at 0x7f8df70c5240>
# 水準方向翻轉
image3 = image[:, ::-1, :]
plt.imshow(image3)
<matplotlib.image.AxesImage at 0x7f8df5817da0>
# 儲存圖檔
im3 = Image.fromarray(image3)
im3.save('/home/zzyy/Pictures/leetcode/im3.jpg')
# 高度方向裁剪
H, W = image.shape[0], image.shape[1]
# 注意此處用整除,H_start必須為整數
H1 = H // 2
H2 = H
image4 = image[H1:H2, :, :]
plt.imshow(image4)
<matplotlib.image.AxesImage at 0x7f8df570add8>
# 寬度方向裁剪
W1 = W//6
W2 = W//3 * 2
image5 = image[:, W1:W2, :]
plt.imshow(image5)
<matplotlib.image.AxesImage at 0x7f8df575ea58>
# 兩個方向同時裁剪
image5 = image[H1:H2, \
W1:W2, :]
plt.imshow(image5)
<matplotlib.image.AxesImage at 0x7f8df5731940>
# 調整亮度
image6 = image * 0.5
plt.imshow(image6.astype('uint8'))
<matplotlib.image.AxesImage at 0x7f8df4dd5518>
# 調整亮度
image7 = image * 2.0
# 由于圖檔的RGB像素值必須在0-255之間,
# 此處使用np.clip進行數值裁剪
image7 = np.clip(image7, a_min=None, a_max=255.)
plt.imshow(image7.astype('uint8'))
<matplotlib.image.AxesImage at 0x7f8df4d15ef0>
#高度方向每隔一行取像素點
image8 = image[::2, :, :]
plt.imshow(image8)
<matplotlib.image.AxesImage at 0x7f8df4cfa908>
#寬度方向每隔一列取像素點
image9 = image[:, ::2, :]
plt.imshow(image9)
<matplotlib.image.AxesImage at 0x7f8df4c61518>
#間隔行列采樣,圖像尺寸會減半,清晰度變差
image10 = image[::2, ::2, :]
plt.imshow(image10)
image10.shape
(306, 306, 3)
參考資料
參考資料