yolov5的数据增强代码来自两个地方:
源码在utils/augmentations.py中,使用了albumentations这个库来处理数据增强,其中处理的细节可以自行搜索使用细节,要是环境中没有安装albumentations库,那么执行时就会跳过这块的数据增强,附源码查看:
class Albumentations:
# YOLOv5 Albumentations class (optional, only used if package is installed)
def __init__(self):
self.transform = None
try:
import albumentations as A
check_version(A.__version__, '1.0.3') # version requirement
self.transform = A.Compose([
A.Blur(p=0.01),
A.MedianBlur(p=0.01),
A.ToGray(p=0.01),
A.CLAHE(p=0.01),
A.RandomBrightnessContrast(p=0.0),
A.RandomGamma(p=0.0),
A.ImageCompression(quality_lower=75, p=0.0)],
bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))
logging.info(colorstr('albumentations: ') + ', '.join(f'{x}' for x in self.transform.transforms if x.p))
except ImportError: # package not installed, skip
pass
except Exception as e:
logging.info(colorstr('albumentations: ') + f'{e}')
def __call__(self, im, labels, p=1.0):
if self.transform and random.random() < p:
new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed
im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])])
return im, labels
2.使用data/hyps/hyp.scratch.ymal中的配置进行数据增强
附上相应的配置和解析说明:
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
hsv_v: 0.4 # image HSV-Value augmentation (fraction) hsv_h,hsv_s,hsv_v配合使用,也可拆分使用
degrees: 10 # image rotation (+/- deg) 旋转[-degrees, +degress]#图像仿射变换的旋转角度, random.uniform(-degrees, degrees)
translate: 0.1 # image translation (+/- fraction) 平移
scale: 0.5 # image scale (+/- gain) #图像仿射变换的缩放比例,random.uniform(1 - scale, 1 + scale) 与degrees配合使用,也可单方面起作用
shear: 0.0 # image shear (+/- deg) #设置裁剪的仿射矩阵系数
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001 0.0:仿射变换,>0为透视变换
flipud: 0.0 # image flip up-down (probability) 单独使用
fliplr: 0.5 # image flip left-right (probability) 单独使用
mosaic: 1.0 # image mosaic (probability) 单独使用
mixup: 0.0 # image mixup (probability) #在mosaic启用时,才可以启用
copy_paste: 0.5 # segment copy-paste (probability) #在mosaic启用时,才可以启用
注意:使用时有些参数是随机比例,有些是变换参数;例如:perspective中设置参数范围为0-0.001,如果看错按照比例来设置,参数过大可能导致模型无法很好收敛,模型效果极差;
反面案例:
原始图片:
perspective:0.5
结果图:
这个没有办法训练了;