Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/utils/augmentations.py
Views: 475
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license1"""2Image augmentation functions3"""45import math6import random78import cv29import numpy as np1011from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box12from utils.metrics import bbox_ioa13from utils.rboxs_utils import poly_filter141516class Albumentations:17# YOLOv5 Albumentations class (optional, only used if package is installed)18def __init__(self):19self.transform = None20try:21import albumentations as A22check_version(A.__version__, '1.0.3', hard=True) # version requirement2324self.transform = A.Compose([25A.Blur(p=0.01),26A.MedianBlur(p=0.01),27A.ToGray(p=0.01),28A.CLAHE(p=0.01),29A.RandomBrightnessContrast(p=0.0),30A.RandomGamma(p=0.0),31A.ImageCompression(quality_lower=75, p=0.0)],32bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))3334LOGGER.info(colorstr('albumentations: ') + ', '.join(f'{x}' for x in self.transform.transforms if x.p))35except ImportError: # package not installed, skip36pass37except Exception as e:38LOGGER.info(colorstr('albumentations: ') + f'{e}')3940def __call__(self, im, labels, p=1.0):41if self.transform and random.random() < p:42new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed43im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])])44return im, labels454647def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):48# HSV color-space augmentation49if hgain or sgain or vgain:50r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains51hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV))52dtype = im.dtype # uint85354x = np.arange(0, 256, dtype=r.dtype)55lut_hue = ((x * r[0]) % 180).astype(dtype)56lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)57lut_val = np.clip(x * r[2], 0, 255).astype(dtype)5859im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))60cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im) # no return needed616263def hist_equalize(im, clahe=True, bgr=False):64# Equalize histogram on BGR image 'im' with im.shape(n,m,3) and range 0-25565yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)66if clahe:67c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))68yuv[:, :, 0] = c.apply(yuv[:, :, 0])69else:70yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram71return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB727374def replicate(im, labels):75# Replicate labels76h, w = im.shape[:2]77boxes = labels[:, 1:].astype(int)78x1, y1, x2, y2 = boxes.T79s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)80for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices81x1b, y1b, x2b, y2b = boxes[i]82bh, bw = y2b - y1b, x2b - x1b83yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y84x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]85im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b] # im4[ymin:ymax, xmin:xmax]86labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)8788return im, labels899091def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):92"""93Resize and pad image while meeting stride-multiple constraints94Returns:95im (array): (height, width, 3)96ratio (array): [w_ratio, h_ratio]97(dw, dh) (array): [w_padding h_padding]98"""99shape = im.shape[:2] # current shape [height, width]100if isinstance(new_shape, int): # [h_rect, w_rect]101new_shape = (new_shape, new_shape)102103# Scale ratio (new / old)104r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])105if not scaleup: # only scale down, do not scale up (for better val mAP)106r = min(r, 1.0)107108# Compute padding109ratio = r, r # wh ratios110new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r)) # w h111dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding112if auto: # minimum rectangle113dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding114elif scaleFill: # stretch115dw, dh = 0.0, 0.0116new_unpad = (new_shape[1], new_shape[0]) # [w h]117ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # [w_ratio, h_ratio]118119dw /= 2 # divide padding into 2 sides120dh /= 2121122if shape[::-1] != new_unpad: # resize123im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)124top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))125left, right = int(round(dw - 0.1)), int(round(dw + 0.1))126im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border127return im, ratio, (dw, dh)128129130def random_perspective(im, targets=(), segments=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0,131border=(0, 0)):132# torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10))133# targets = [cls, xyxyxyxy]134135height = im.shape[0] + border[0] * 2 # shape(h,w,c)136width = im.shape[1] + border[1] * 2137138# Center139C = np.eye(3)140C[0, 2] = -im.shape[1] / 2 # x translation (pixels)141C[1, 2] = -im.shape[0] / 2 # y translation (pixels)142143# Perspective144P = np.eye(3)145P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)146P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)147148# Rotation and Scale149R = np.eye(3)150a = random.uniform(-degrees, degrees)151# a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations152s = random.uniform(1 - scale, 1 + scale)153# s = 2 ** random.uniform(-scale, scale)154R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)155156# Shear157S = np.eye(3)158S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)159S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)160161# Translation162T = np.eye(3)163T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)164T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)165166# Combined rotation matrix167M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT168if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed169if perspective:170im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))171else: # affine172im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))173174# Visualize175# import matplotlib.pyplot as plt176# ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()177# ax[0].imshow(im[:, :, ::-1]) # base178# ax[1].imshow(im2[:, :, ::-1]) # warped179180# Transform label coordinates181n = len(targets)182if n:183use_segments = any(x.any() for x in segments)184new = np.zeros((n, 4))185if use_segments: # warp segments186segments = resample_segments(segments) # upsample187for i, segment in enumerate(segments):188xy = np.ones((len(segment), 3))189xy[:, :2] = segment190xy = xy @ M.T # transform191xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine192193# clip194new[i] = segment2box(xy, width, height)195196else: # warp boxes197xy = np.ones((n * 4, 3))198# xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1199xy[:, :2] = targets[:, 1:].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1200xy = xy @ M.T # transform201xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine202203# # create new boxes204# x = xy[:, [0, 2, 4, 6]]205# y = xy[:, [1, 3, 5, 7]]206# new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T207208# # clip209# new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)210# new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)211# clip boxes 不启用,保留预测完整物体的能力212213# filter candidates214# i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)215# targets = targets[i]216# targets[:, 1:5] = new[i]217targets_mask = poly_filter(polys=xy, h=height, w=width)218targets[:, 1:] = xy219targets = targets[targets_mask]220221return im, targets222223224def copy_paste(im, labels, segments, p=0.5):225# Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)226n = len(segments)227if p and n:228h, w, c = im.shape # height, width, channels229im_new = np.zeros(im.shape, np.uint8)230for j in random.sample(range(n), k=round(p * n)):231l, s = labels[j], segments[j]232box = w - l[3], l[2], w - l[1], l[4]233ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area234if (ioa < 0.30).all(): # allow 30% obscuration of existing labels235labels = np.concatenate((labels, [[l[0], *box]]), 0)236segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))237cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)238239result = cv2.bitwise_and(src1=im, src2=im_new)240result = cv2.flip(result, 1) # augment segments (flip left-right)241i = result > 0 # pixels to replace242# i[:, :] = result.max(2).reshape(h, w, 1) # act over ch243im[i] = result[i] # cv2.imwrite('debug.jpg', im) # debug244245return im, labels, segments246247248def cutout(im, labels, p=0.5):249# Applies image cutout augmentation https://arxiv.org/abs/1708.04552250if random.random() < p:251h, w = im.shape[:2]252scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction253for s in scales:254mask_h = random.randint(1, int(h * s)) # create random masks255mask_w = random.randint(1, int(w * s))256257# box258xmin = max(0, random.randint(0, w) - mask_w // 2)259ymin = max(0, random.randint(0, h) - mask_h // 2)260xmax = min(w, xmin + mask_w)261ymax = min(h, ymin + mask_h)262263# apply random color mask264im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]265266# return unobscured labels267if len(labels) and s > 0.03:268box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)269ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area270labels = labels[ioa < 0.60] # remove >60% obscured labels271272return labels273274275def mixup(im, labels, im2, labels2):276# Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf277r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0278im = (im * r + im2 * (1 - r)).astype(np.uint8)279labels = np.concatenate((labels, labels2), 0)280return im, labels281282283def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)284# Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio285w1, h1 = box1[2] - box1[0], box1[3] - box1[1]286w2, h2 = box2[2] - box2[0], box2[3] - box2[1]287ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio288return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates289290291