当我们使用深度学习进行训练时,数据集如果不充足,会想到去扩充数据。下面我们就介绍五种常用的扩充方法。
import cv2'''1. 旋转'''
def cv2_rotation(img, angle): '''输入图像、要旋转的角度'''(h, w) = img.shape[:2]center = (w // 2, h // 2)M = cv2.getRotationMatrix2D(center, angle, 1.)rotated = cv2.warpAffine(img, M, (w, h))return rotated'''2. 反转'''
img1 = cv2.flip(img, 0) # 水平翻转
img2 = cv2.flip(img, 1) # 垂直反转
img3 = cv2.flip(img, -1) # 水平垂直反转
对上述的旋转和反转做不同的组合,可以得到,
from PIL import Image, ImageEnhance
import cv2
import numpy as npdef randomColor(image): # 图像增强# 亮度变化enh_bri = ImageEnhance.Brightness(image)brightness = np.random.randint(8, 13) / 10. # 随机因子image1 = enh_bri.enhance(brightness)# 色度变化enh_col = ImageEnhance.Color(image1)color = np.random.randint(5, 25) / 10. # 随机因子image2 = enh_col.enhance(color)# 对比度变化enh_con = ImageEnhance.Contrast(image2)contrast = np.random.randint(8, 25) / 10. # 随机因子image3 = enh_con.enhance(contrast)# 锐度变化enh_sha = ImageEnhance.Sharpness(image3)sharpness = np.random.randint(5, 51) / 10. # 随机因子image4 = enh_sha.enhance(sharpness)return image4
针对一个图像,我们可以
这样就可以实现图像数据的扩充。当然这里还没有包括一些裁剪,mask的操作,因为我的任务不同。