序言
使用Augly库写了一个易用的图像增强函数,用来扩充图像样本,增加样本的多样性,使用起来非常简单,需要预先安装Augly库,在终端中运行:
pip install augly
全部代码分享如下(代码还有优化空间,根据自己需要进行优化):
import os
import random
import augly.image as imaugs
import PIL.Image as Image
img_path = "img"
save_path = "save"
def augly_augmentation(aug_image):
aug = [
imaugs.blur(aug_image,radius=random.randint(1,2)),
imaugs.brightness(aug_image,factor=random.uniform(0.5,1.5)),
imaugs.change_aspect_ratio(aug_image, ratio=random.uniform(0.8,1.5)),
imaugs.color_jitter(aug_image, brightness_factor=random.uniform(0.8,1.5), contrast_factor=random.uniform(0.8,1.5), saturation_factor=random.uniform(0.8,1.5)),
imaugs.crop(aug_image, x1=random.uniform(0,0.1), y1=random.uniform(0,0.1), x2=random.uniform(0.9,1), y2=random.uniform(0.9,1)),
imaugs.hflip(aug_image),
imaugs.opacity(aug_image, level=random.uniform(0.5,1)),
imaugs.pixelization(aug_image, ratio=random.uniform(0.5,1)),
imaugs.random_noise(aug_image),
imaugs.rotate(aug_image, degrees=random.randint(3,10)),
imaugs.shuffle_pixels(aug_image, factor=random.uniform(0,0.1)),
imaugs.saturation(aug_image, factor=random.uniform(1,1.5)),
imaugs.contrast(aug_image, factor=random.uniform(1,1.5)),
imaugs.grayscale(aug_image)
]
return random.choice(aug)
for name in os.listdir(img_path):
aug_image = Image.open(os.path.join(img_path,name))
count = 3
for i in range(count):
image = augly_augmentation(aug_image)
image = image.convert("RGB")
image.save(os.path.join(save_path,name[:-4]+"_{}.jpg".format(i)))
使用示例
原始图像为: 随机增强后示例:
改变图像饱和度:
一定范围内随机改变长宽比:
随机噪声:
还可以在加载数据集时在训练中随机增强:
关于augly更多使用可以参考以前的文章:facebook最近开源的python图像增强库—Augly
|