Python 数据增强 – PIL模块
一、导入模块、读取图片
# 图像操作模块
from PIL import Image
# 图像颜色增强模块
from PIL import ImageEnhance
#读取图像
img = Image.open("lenna.jpg")
img.show()
二、几何增强
1、缩放
# 指定所需的尺寸
im_resized = im.resize((128, 128))
2、旋转
# 指定逆时针旋转的角度(°)
img_rotate = img.rotate(45)
3、翻转
# 左右翻转
out = img.transpose(Image.FLIP_LEFT_RIGHT)
# 上下翻转
out = img.transpose(Image.FLIP_TOP_BOTTOM)
# 旋转
out = img.transpose(Image.ROTATE_90)
三、颜色增强
1、亮度增强
# 增强因子为0.0产生黑色图像,为1.0保持原始图像
brightness_factor = np.random.randint(8, 16) / 10
brightness_image = ImageEnhance.Brightness(img).enhance(brightness_factor)
2、对比度增强
contrast_factor = np.random.randint(8, 16) / 10
contrast_image = ImageEnhance.Contrast(img).enhance(contrast_factor)
3、色彩饱和度增强
color_factor = np.random.randint(5, 15) / 10
color_image = ImageEnhance.Color(img).enhance(color_factor)
4、锐度增强
sharp_factor = np.random.randint(8, 12) / 10
sharp_image = ImageEnhance.Sharpness(img).enhance(sharp_factor)