在進行圖像領域的深度學習的時候經常需要對圖檔進行處理,包括圖像的翻轉,壓縮,截取等,一般都是用Numpy來處理。處理起來也很友善。
In[3]
導入需要的包
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
讀入圖檔
image = Image.open('./work/vehicle1.jpg')
image = np.array(image)
檢視資料形狀,其形狀是[H, W, 3],
其中H代表高度, W是寬度,3代表RGB三個通道
image.shape
(437, 700, 3)
In[4]
原始圖檔
plt.imshow(image)
?
In[7]
垂直方向翻轉
這裡使用數組切片的方式來完成,
相當于将圖檔最後一行挪到第一行,
倒數第二行挪到第二行,...,
第一行挪到倒數第一行
對于行名額,使用::-1來表示切片,
負數步長表示以最後一個元素為起點,向左走尋找下一個點
對于列名額和RGB通道,僅使用:表示該次元不改變
image2 = image[::-1, :, :]
plt.imshow(image2)
In[8]
水準方向翻轉
image3 = image[:, ::-1, :]
plt.imshow(image3)
In[5]
180度方向翻轉
image31 = image[::-1, ::-1, :]
plt.imshow(image31)
In[9]
儲存圖檔
im3 = Image.fromarray(image3)
im3.save('im3.jpg')
In[10]
高度方向裁剪
H, W = image.shape[0], image.shape[1]
注意此處用整除,H_start必須為整數
H1 = H // 2
H2 = H
image4 = image[H1:H2, :, :]
plt.imshow(image4)
In[11]
寬度方向裁剪
W1 = W//6
W2 = W//3 * 2
image5 = image[:, W1:W2, :]
plt.imshow(image5)
In[13]
兩個方向同時裁剪
image5 = image[H1:H2, \
W1:W2, :]
In[14]
調整亮度
image6 = image * 0.5
plt.imshow(image6.astype('uint8'))
In[15]
image7 = image * 2.0
由于圖檔的RGB像素值必須在0-255之間,
此處使用np.clip進行數值裁剪
image7 = np.clip(image7, \
a_min=None, a_max=255.)
plt.imshow(image7.astype('uint8'))
In[16]
高度方向每隔一行取像素點
image8 = image[::2, :, :]
plt.imshow(image8)
In[17]
寬度方向每隔一列取像素點
image9 = image[:, ::2, :]
plt.imshow(image9)
In[18]
間隔行列采樣,圖像尺寸會減半,清晰度變差
image10 = image[::2, ::2, :]
plt.imshow(image10)
image10.shape
(219, 350, 3)