目的
在深度學習中,我們需要大量的數據,但是通常直接在現實中獲取數據的難度很高,成本也非常高,時間耗費也一樣讓人難以承受。
所以大家就想,能不能把現有的數據進行人工處理一下,產生人造新數據,達到增加訓練數據的目的呢?
這就是我們所謂的數據增強!
而本文會通過最簡單的方法,告訴大家如何用 3 個常用模塊,來實現圖像領域的數據增強!
所需 Python 模塊
這裏我們用到的是:
- numpy,這個就不解釋了!
- matplotlib.pyplot,這個主要是用來顯示圖片
- PIL,這個是對圖片進行變化操作
案例
Talk is cheap, show me the code!
# 導入需要的包
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import os
# 獲取當前的路徑
currentpath = os.getcwd()
print(currentpath)
# 讀入圖片
image = Image.open('./cat.jpg')
image = np.array(image)
# 查看數據形狀,其形狀是[H, W, 3],
# 其中H代表高度, W是寬度,3代表RGB三個通道
image.shape
首先顯示原始圖片:
# 原始圖片
plt.imshow(image)
然後獲取垂直翻轉後的圖片:
# 垂直方向翻轉
# 這裏使用數組切片的方式來完成,
# 相當於將圖片最後一行挪到第一行,
# 倒數第二行挪到第二行,...,
# 第一行挪到倒數第一行
# 對於行指標,使用::-1來表示切片,
# 負數步長表示以最後一個元素爲起點,向左走尋找下一個點
img2 = image[::-1, :, :]
plt.imshow(img2)
# 水平方向翻轉
img3 = image[:, ::-1, :]
plt.imshow(img3)
# 高度方向裁剪
H, W = image.shape[0], image.shape[1]
# 注意此處用整除,像素位置必須爲整數
H1 = H // 2
img4 = image[0:H1, :, :]
plt.imshow(img4)
# 寬度方向裁剪
W1 = W//6
W2 = W//3 * 2
img5 = image[:, W1:W2, :]
plt.imshow(img5)
# 兩個方向同時裁剪
img6 = image[0:H1, W1:W2, :]
plt.imshow(img6)
# 調整亮度
img7 = image * 0.5
plt.imshow(img7.astype('uint8'))
# 調整亮度
img8 = image * 2.0
# 由於圖片的RGB像素值必須在0-255之間,
# 此處使用np.clip進行數值裁剪
img8 = np.clip(img8, a_min=None, a_max=255.)
plt.imshow(img8.astype('uint8'))
#高度方向每隔一行採樣
img9 = image[::2, :, :]
plt.imshow(img9)
#寬度方向每隔一列採樣
img10 = image[:, ::2, :]
plt.imshow(img10)
#間隔行列採樣,圖像尺寸減半,清晰度減半
img11 = image[::2, ::2, :]
plt.imshow(img11)
img11.shape
我們調整後的圖片存貯下來:
# 保存圖片
img_3 = Image.fromarray(img3)
img_3.save('img3.jpg')
在批量操作的時候,可以考慮綜合應用文件路徑操作,或者正則表達式,可以很容易完成。大家有什麼疑問歡迎留言探討!