图像增广不仅可以扩大训练数据集的规模,还能够随机改变训练样本可以降低模型对某些属性的依赖,从而提高模型的泛化能力。
首先导入包。
%matplotlib inline
import mxnet as mx
from IPython import display
from mxnet import autograd, gluon, image, init, nd
from mxnet.gluon import data as gdata, loss as gloss, utils as gutils
from matplotlib import pyplot as plt
import sys
import time
定义一个设置绘图大小的函数。
def set_figsize(figsize=(3.5, 2.5)):
display.set_matplotlib_formats('svg')
plt.rcParams['figure.figsize'] = figsize
读入一幅图像并显示。
set_figsize()
img = image.imread('img/dog.jpg')
plt.imshow(img.asnumpy())
定义一个绘图函数。
def show_images(imgs, num_rows, num_cols, scale=2):
figsize = (num_cols * scale, num_rows * scale)
_, axes = plt.subplots(num_rows, num_cols, figsize=figsize)
for i in range(num_rows):
for j in range(num_cols):
axes[i][j].imshow(imgs[i * num_cols + j].asnumpy())
axes[i][j].axes.get_xaxis().set_visible(False)
axes[i][j].axes.get_yaxis().set_visible(False)
return axes
定义一个辅助函数对输入图像做图像增广。
def apply(img, aug, num_rows=2, num_cols=4, scale=1.5):
Y = [aug(img) for _ in range(num_rows * num_cols)]
show_images(Y, num_rows, num_cols, scale)
对图像做随机左右翻转。
apply(img, gdata.vision.transforms.RandomFlipLeftRight())
随机上下翻转。
apply(img, gdata.vision.transforms.RandomFlipTopBottom())
随机裁剪。每次随机裁剪出一块面积为原面积10%∼100%的区域,且该区域的宽和高之比随机取自0.5∼2,然后再将该区域的宽和高分别缩放到200像素。
shape_aug = gdata.vision.transforms.RandomResizedCrop((200, 200), scale=(0.1, 1), ratio=(0.5, 2))
apply(img, shape_aug)
将图像的亮度随机变化为原图亮度的50%∼150%((1 - 0.5)~ (1 + 0.5))。
apply(img, gdata.vision.transforms.RandomBrightness(0.5))
将图像的亮度随机变化为原图色度的50%∼150%((1 - 0.5)~ (1 + 0.5))。
apply(img, gdata.vision.transforms.RandomHue(0.5))
同时设置随机变化图像的亮度、对比度、饱和度和色调。
color_aug = gdata.vision.transforms.RandomColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5)
apply(img, color_aug)
将多个图像增广方法叠加使用。
augs = gdata.vision.transforms.Compose([gdata.vision.transforms.RandomFlipLeftRight(), color_aug, shape_aug])
apply(img, augs)