数据增强的⽅法总结及代码实现
在训练模型的时候,经常会出现数据不够多,如此就会出现过拟合等问题,通过对训练图⽚进⾏变换可以得到泛化能⼒更强的⽹络,更好的适应应⽤场景。博主⽤⾃⼰项⽬中常⽤的⼀些⽅法代码写出来。
⼀、数据增强⽅法总结
1、平移。在图像平⾯上对图像以⼀定⽅式进⾏平移。
2、翻转图像。沿着⽔平或者垂直⽅向翻转图像。
3、旋转⾓度。随机旋转图像⼀定⾓度; 改变图像内容的朝向。
bootstrapping4、随机颜⾊。对图像进⾏颜⾊抖动,对图像的每个像素RGB进⾏随机扰动, 常⽤的噪声模式是椒盐噪声和⾼斯噪声。
ralphlauren5、对⽐度增强。增强图像对⽐度,也可以⽤直⽅图均衡化。
6、亮度增强。将整个图像亮度调⾼。
7、颜⾊增强。
8、还有随机裁剪、尺度变换等代码就不赘述了。hkma
⼆、数据增强⽅法代码
1、平移
from PIL import Image
from PIL import ImageEnhance
import os
import cv2
import numpy as np
def move(root_path,img_name,off): #平移,平移尺度为off
img = Image.open(os.path.join(root_path, img_name))
offt = img.offt(off,0)
return offt
indifferent
2、翻转图像
def flip(root_path,img_name): #翻转图像
img = Image.open(os.path.join(root_path, img_name))
filp_img = anspo(Image.FLIP_LEFT_RIGHT)
# filp_img.save(os.path.join(root_path,img_name.split('.')[0] + '_flip.jpg'))
return filp_img
3、旋转⾓度
asapdef rotation(root_path, img_name):
img = Image.open(os.path.join(root_path, img_name))
rotation_img = ate(20) #旋转⾓度
# rotation_img.save(os.path.join(root_path,img_name.split('.')[0] + '_rotation.jpg'))
return rotation_img
4、随机颜⾊
zzipdef randomColor(root_path, img_name): #随机颜⾊
"""
对图像进⾏颜⾊抖动
:param image: PIL的图像image
:return: 有颜⾊⾊差的图像image
"""
image = Image.open(os.path.join(root_path, img_name))
random_factor = np.random.randint(0, 31) / 10. # 随机因⼦
color_image = ImageEnhance.Color(image).enhance(random_factor) # 调整图像的饱和度
random_factor = np.random.randint(10, 21) / 10. # 随机因⼦
brightness_image = ImageEnhance.Brightness(color_image).enhance(random_factor) # 调整图像的亮度 random_factor = np.random.randint(10, 21) / 10. # 随机因⼦
contrast_image = ImageEnhance.Contrast(brightness_image).enhance(random_factor) # 调整图像对⽐度 random_factor = np.random.randint(0, 31) / 10. # 随机因⼦
return ImageEnhance.Sharpness(contrast_image).enhance(random_factor) # 调整图像锐度
5、对⽐度增强
def contrastEnhancement(root_path,img_name):#对⽐度增强
image = Image.open(os.path.join(root_path, img_name))
遥控器英语enh_con = ImageEnhance.Contrast(image)
contrast = 1.5
image_contrasted = hance(contrast)
推迟英文return image_contrasted
6、亮度增强
def brightnessEnhancement(root_path,img_name):#亮度增强
image = Image.open(os.path.join(root_path, img_name))
enh_bri = ImageEnhance.Brightness(image)
brightness = 1.5
image_brightened = hance(brightness)
return image_brightened
7、颜⾊增强
def colorEnhancement(root_path,img_name):#颜⾊增强
image = Image.open(os.path.join(root_path, img_name))
enh_col = ImageEnhance.Color(image)
color = 1.5
image_colored = hance(color)
return image_colored
三、⼯程具体实现代码
注意:
ait1、将下列代码中flip函数换成你要实现的数据增强⽅法的名字即可。
2、包含的库必须要包含
from PIL import Image
讲师英文
from PIL import ImageEnhance
import os
import cv2
import numpy as np
imageDir="C:/Urs/Administrator/Desktop/right/" #要改变的图⽚的路径⽂件夹saveDir="C:/Urs/Administrator/Desktop/save/" #要保存的图⽚的路径⽂件夹i=0
for name in os.listdir(imageDir):
i=i+1
saveName="car"+str(i)+".jpg"
saveImage=flip(imageDir,name)
saveImage.save(os.path.join(saveDir,saveName))