本代码共采用了四种数据增强,如采用其他数据增强方式,可以参考本代码,随意替换。
'''
imageDir 为原数据集的存放位置
saveDir 为数据增强后数据的存放位置
'''
from PIL import Image
from PIL import ImageEnhance
import os
import cv2
import numpy as np
import glob
def flip(root_path): #翻转图像
img = Image.open(root_path)
filp_img = img.transpose(Image.FLIP_LEFT_RIGHT)
return filp_img
def rotation(root_path):
img = Image.open(root_path)
rotation_img = img.rotate(90) #旋转角度
return rotation_img
def brightnessEnhancement(root_path):#亮度增强
image = Image.open(root_path)
enh_bri = ImageEnhance.Brightness(image)
brightness = 1.5
image_brightened = enh_bri.enhance(brightness)
return image_brightened
def contrastEnhancement(root_path): # 对比度增强
image = Image.open(root_path)
enh_con = ImageEnhance.Contrast(image)
contrast = 1.5
image_contrasted = enh_con.enhance(contrast)
return image_contrasted
def colorEnhancement(root_path):#颜色增强
image = Image.open(root_path)
enh_col = ImageEnhance.Color(image)
color = 1.5
image_colored = enh_col.enhance(color)
return image_colored
def randomColor(root_path): #随机颜色
"""
对图像进行颜色抖动
:param image: PIL的图像image
:return: 有颜色色差的图像image
"""
image = Image.open(root_path)
random_factor = np.random.randint(0, 31) / 10. # 随机因子
color_image = ImageEnhance.Color(image).enhance(random_fa

该代码展示了如何使用Python的PIL库进行图像的数据增强,包括翻转、旋转、亮度和对比度增强、颜色增强以及随机颜色调整。适用于图像分类任务,能对多类别文件夹中的图像统一进行数据增强。

1607

被折叠的 条评论
为什么被折叠?



