Diff of /utils/augmentations.py [000000] .. [190ca4]

Switch to unified view

a b/utils/augmentations.py
1
# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
2
"""
3
Image augmentation functions
4
"""
5
6
import math
7
import random
8
9
import cv2
10
import numpy as np
11
import torch
12
import torchvision.transforms as T
13
import torchvision.transforms.functional as TF
14
from PIL import Image
15
16
17
from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box, xywhn2xyxy
18
from utils.metrics import bbox_ioa
19
20
IMAGENET_MEAN = 0.485, 0.456, 0.406  # RGB mean
21
IMAGENET_STD = 0.229, 0.224, 0.225  # RGB standard deviation
22
23
24
class Albumentations:
25
    # YOLOv5 Albumentations class (optional, only used if package is installed)
26
    def __init__(self, size=640):
27
        self.transform = None
28
        prefix = colorstr('albumentations: ')
29
        try:
30
            import albumentations as A
31
            check_version(A.__version__, '1.0.3', hard=True)  # version requirement
32
33
            T = [
34
                A.RandomResizedCrop(height=size, width=size, scale=(0.8, 1.0), ratio=(0.9, 1.11), p=0.0),
35
                A.Blur(p=0.01),
36
                A.MedianBlur(p=0.01),
37
                A.ToGray(p=0.01),
38
                A.CLAHE(p=0.01),
39
                A.RandomBrightnessContrast(p=0.0),
40
                A.RandomGamma(p=0.0),
41
                A.ImageCompression(quality_lower=75, p=0.0)]  # transforms
42
            self.transform = A.Compose(T, bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))
43
44
            LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))
45
        except ImportError:  # package not installed, skip
46
            pass
47
        except Exception as e:
48
            LOGGER.info(f'{prefix}{e}')
49
50
    def __call__(self, im, labels, p=1.0):
51
        if self.transform and random.random() < p:
52
            new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0])  # transformed
53
            im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])])
54
        return im, labels
55
56
57
def normalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD, inplace=False):
58
    # Denormalize RGB images x per ImageNet stats in BCHW format, i.e. = (x - mean) / std
59
    return TF.normalize(x, mean, std, inplace=inplace)
60
61
62
def denormalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD):
63
    # Denormalize RGB images x per ImageNet stats in BCHW format, i.e. = x * std + mean
64
    for i in range(3):
65
        x[:, i] = x[:, i] * std[i] + mean[i]
66
    return x
67
68
69
def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):
70
    # HSV color-space augmentation
71
    if hgain or sgain or vgain:
72
        r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1  # random gains
73
        hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV))
74
        dtype = im.dtype  # uint8
75
76
        x = np.arange(0, 256, dtype=r.dtype)
77
        lut_hue = ((x * r[0]) % 180).astype(dtype)
78
        lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
79
        lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
80
81
        im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))
82
        cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im)  # no return needed
83
84
85
def hist_equalize(im, clahe=True, bgr=False):
86
    # Equalize histogram on BGR image 'im' with im.shape(n,m,3) and range 0-255
87
    yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
88
    if clahe:
89
        c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
90
        yuv[:, :, 0] = c.apply(yuv[:, :, 0])
91
    else:
92
        yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0])  # equalize Y channel histogram
93
    return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB)  # convert YUV image to RGB
94
95
96
def replicate(im, labels):
97
    # Replicate labels
98
    h, w = im.shape[:2]
99
    boxes = labels[:, 1:].astype(int)
100
    x1, y1, x2, y2 = boxes.T
101
    s = ((x2 - x1) + (y2 - y1)) / 2  # side length (pixels)
102
    for i in s.argsort()[:round(s.size * 0.5)]:  # smallest indices
103
        x1b, y1b, x2b, y2b = boxes[i]
104
        bh, bw = y2b - y1b, x2b - x1b
105
        yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw))  # offset x, y
106
        x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
107
        im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b]  # im4[ymin:ymax, xmin:xmax]
108
        labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
109
110
    return im, labels
111
112
113
def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
114
    # Resize and pad image while meeting stride-multiple constraints
115
    shape = im.shape[:2]  # current shape [height, width]
116
    if isinstance(new_shape, int):
117
        new_shape = (new_shape, new_shape)
118
119
    # Scale ratio (new / old)
120
    r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
121
    if not scaleup:  # only scale down, do not scale up (for better val mAP)
122
        r = min(r, 1.0)
123
124
    # Compute padding
125
    ratio = r, r  # width, height ratios
126
    new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
127
    dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding
128
    if auto:  # minimum rectangle
129
        dw, dh = np.mod(dw, stride), np.mod(dh, stride)  # wh padding
130
    elif scaleFill:  # stretch
131
        dw, dh = 0.0, 0.0
132
        new_unpad = (new_shape[1], new_shape[0])
133
        ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios
134
135
    dw /= 2  # divide padding into 2 sides
136
    dh /= 2
137
138
    if shape[::-1] != new_unpad:  # resize
139
        im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
140
        # pil_img = Image.fromarray(im)
141
        # image = pil_img.resize(new_shape, Image.LANCZOS)
142
        # im = np.array(image)
143
144
145
    top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
146
    left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
147
    im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)  # add border
148
    # ratio = (1.0, 1.0)
149
150
    # # Set dw and dh to 0.0
151
    # dw = 0.0
152
    # dh = 0.0
153
154
    return im, ratio, (dw, dh)
155
156
157
def random_perspective(im,
158
                       targets=(),
159
                       segments=(),
160
                       degrees=10,
161
                       translate=.1,
162
                       scale=.1,
163
                       shear=10,
164
                       perspective=0.0,
165
                       border=(0, 0)):
166
    # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10))
167
    # targets = [cls, xyxy]
168
169
    height = im.shape[0] + border[0] * 2  # shape(h,w,c)
170
    width = im.shape[1] + border[1] * 2
171
172
    # Center
173
    C = np.eye(3)
174
    C[0, 2] = -im.shape[1] / 2  # x translation (pixels)
175
    C[1, 2] = -im.shape[0] / 2  # y translation (pixels)
176
177
    # Perspective
178
    P = np.eye(3)
179
    P[2, 0] = random.uniform(-perspective, perspective)  # x perspective (about y)
180
    P[2, 1] = random.uniform(-perspective, perspective)  # y perspective (about x)
181
182
    # Rotation and Scale
183
    R = np.eye(3)
184
    a = random.uniform(-degrees, degrees)
185
    # a += random.choice([-180, -90, 0, 90])  # add 90deg rotations to small rotations
186
    s = random.uniform(1 - scale, 1 + scale)
187
    # s = 2 ** random.uniform(-scale, scale)
188
    R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
189
190
    # Shear
191
    S = np.eye(3)
192
    S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180)  # x shear (deg)
193
    S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180)  # y shear (deg)
194
195
    # Translation
196
    T = np.eye(3)
197
    T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width  # x translation (pixels)
198
    T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height  # y translation (pixels)
199
200
    # Combined rotation matrix
201
    M = T @ S @ R @ P @ C  # order of operations (right to left) is IMPORTANT
202
    if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any():  # image changed
203
        if perspective:
204
            im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))
205
        else:  # affine
206
            im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
207
208
    # Visualize
209
    # import matplotlib.pyplot as plt
210
    # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
211
    # ax[0].imshow(im[:, :, ::-1])  # base
212
    # ax[1].imshow(im2[:, :, ::-1])  # warped
213
214
    # Transform label coordinates
215
    n = len(targets)
216
    if n:
217
        use_segments = any(x.any() for x in segments) and len(segments) == n
218
        new = np.zeros((n, 4))
219
        if use_segments:  # warp segments
220
            segments = resample_segments(segments)  # upsample
221
            for i, segment in enumerate(segments):
222
                xy = np.ones((len(segment), 3))
223
                xy[:, :2] = segment
224
                xy = xy @ M.T  # transform
225
                xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]  # perspective rescale or affine
226
227
                # clip
228
                new[i] = segment2box(xy, width, height)
229
230
        else:  # warp boxes
231
            xy = np.ones((n * 4, 3))
232
            xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2)  # x1y1, x2y2, x1y2, x2y1
233
            xy = xy @ M.T  # transform
234
            xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8)  # perspective rescale or affine
235
236
            # create new boxes
237
            x = xy[:, [0, 2, 4, 6]]
238
            y = xy[:, [1, 3, 5, 7]]
239
            new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
240
241
            # clip
242
            new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
243
            new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
244
245
        # filter candidates
246
        i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
247
        targets = targets[i]
248
        targets[:, 1:5] = new[i]
249
250
    return im, targets
251
252
253
def copy_paste(im, labels, segments, p=0.5):
254
    # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
255
    n = len(segments)
256
    if p and n:
257
        h, w, c = im.shape  # height, width, channels
258
        im_new = np.zeros(im.shape, np.uint8)
259
        for j in random.sample(range(n), k=round(p * n)):
260
            l, s = labels[j], segments[j]
261
            box = w - l[3], l[2], w - l[1], l[4]
262
            ioa = bbox_ioa(box, labels[:, 1:5])  # intersection over area
263
            if (ioa < 0.30).all():  # allow 30% obscuration of existing labels
264
                labels = np.concatenate((labels, [[l[0], *box]]), 0)
265
                segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))
266
                cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (1, 1, 1), cv2.FILLED)
267
268
        result = cv2.flip(im, 1)  # augment segments (flip left-right)
269
        i = cv2.flip(im_new, 1).astype(bool)
270
        im[i] = result[i]  # cv2.imwrite('debug.jpg', im)  # debug
271
272
    return im, labels, segments
273
274
275
def cutout(im, labels, p=0.5):
276
    # Applies image cutout augmentation https://arxiv.org/abs/1708.04552
277
    if random.random() < p:
278
        h, w = im.shape[:2]
279
        scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16  # image size fraction
280
        for s in scales:
281
            mask_h = random.randint(1, int(h * s))  # create random masks
282
            mask_w = random.randint(1, int(w * s))
283
284
            # box
285
            xmin = max(0, random.randint(0, w) - mask_w // 2)
286
            ymin = max(0, random.randint(0, h) - mask_h // 2)
287
            xmax = min(w, xmin + mask_w)
288
            ymax = min(h, ymin + mask_h)
289
290
            # apply random color mask
291
            im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
292
293
            # return unobscured labels
294
            if len(labels) and s > 0.03:
295
                box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
296
                ioa = bbox_ioa(box, xywhn2xyxy(labels[:, 1:5], w, h))  # intersection over area
297
                labels = labels[ioa < 0.60]  # remove >60% obscured labels
298
299
    return labels
300
301
302
def mixup(im, labels, im2, labels2):
303
    # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf
304
    r = np.random.beta(32.0, 32.0)  # mixup ratio, alpha=beta=32.0
305
    im = (im * r + im2 * (1 - r)).astype(np.uint8)
306
    labels = np.concatenate((labels, labels2), 0)
307
    return im, labels
308
309
310
def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16):  # box1(4,n), box2(4,n)
311
    # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
312
    w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
313
    w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
314
    ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps))  # aspect ratio
315
    return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr)  # candidates
316
317
318
def classify_albumentations(
319
        augment=True,
320
        size=224,
321
        scale=(0.08, 1.0),
322
        ratio=(0.75, 1.0 / 0.75),  # 0.75, 1.33
323
        hflip=0.5,
324
        vflip=0.0,
325
        jitter=0.4,
326
        mean=IMAGENET_MEAN,
327
        std=IMAGENET_STD,
328
        auto_aug=False):
329
    # YOLOv5 classification Albumentations (optional, only used if package is installed)
330
    prefix = colorstr('albumentations: ')
331
    try:
332
        import albumentations as A
333
        from albumentations.pytorch import ToTensorV2
334
        check_version(A.__version__, '1.0.3', hard=True)  # version requirement
335
        if augment:  # Resize and crop
336
            T = [A.RandomResizedCrop(height=size, width=size, scale=scale, ratio=ratio)]
337
            if auto_aug:
338
                # TODO: implement AugMix, AutoAug & RandAug in albumentation
339
                LOGGER.info(f'{prefix}auto augmentations are currently not supported')
340
            else:
341
                if hflip > 0:
342
                    T += [A.HorizontalFlip(p=hflip)]
343
                if vflip > 0:
344
                    T += [A.VerticalFlip(p=vflip)]
345
                if jitter > 0:
346
                    color_jitter = (float(jitter), ) * 3  # repeat value for brightness, contrast, satuaration, 0 hue
347
                    T += [A.ColorJitter(*color_jitter, 0)]
348
        else:  # Use fixed crop for eval set (reproducibility)
349
            T = [A.SmallestMaxSize(max_size=size), A.CenterCrop(height=size, width=size)]
350
        T += [A.Normalize(mean=mean, std=std), ToTensorV2()]  # Normalize and convert to Tensor
351
        LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))
352
        return A.Compose(T)
353
354
    except ImportError:  # package not installed, skip
355
        LOGGER.warning(f'{prefix}⚠️ not found, install with `pip install albumentations` (recommended)')
356
    except Exception as e:
357
        LOGGER.info(f'{prefix}{e}')
358
359
360
def classify_transforms(size=224):
361
    # Transforms to apply if albumentations not installed
362
    assert isinstance(size, int), f'ERROR: classify_transforms size {size} must be integer, not (list, tuple)'
363
    # T.Compose([T.ToTensor(), T.Resize(size), T.CenterCrop(size), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])
364
    return T.Compose([CenterCrop(size), ToTensor(), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])
365
366
367
class LetterBox:
368
    # YOLOv5 LetterBox class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])
369
    def __init__(self, size=(640, 640), auto=False, stride=32):
370
        super().__init__()
371
        self.h, self.w = (size, size) if isinstance(size, int) else size
372
        self.auto = auto  # pass max size integer, automatically solve for short side using stride
373
        self.stride = stride  # used with auto
374
375
    def __call__(self, im):  # im = np.array HWC
376
        imh, imw = im.shape[:2]
377
        r = min(self.h / imh, self.w / imw)  # ratio of new/old
378
        h, w = round(imh * r), round(imw * r)  # resized image
379
        hs, ws = (math.ceil(x / self.stride) * self.stride for x in (h, w)) if self.auto else self.h, self.w
380
        top, left = round((hs - h) / 2 - 0.1), round((ws - w) / 2 - 0.1)
381
        im_out = np.full((self.h, self.w, 3), 114, dtype=im.dtype)
382
        im_out[top:top + h, left:left + w] = cv2.resize(im, (w, h), interpolation=cv2.INTER_LINEAR)
383
        return im_out
384
385
386
class CenterCrop:
387
    # YOLOv5 CenterCrop class for image preprocessing, i.e. T.Compose([CenterCrop(size), ToTensor()])
388
    def __init__(self, size=640):
389
        super().__init__()
390
        self.h, self.w = (size, size) if isinstance(size, int) else size
391
392
    def __call__(self, im):  # im = np.array HWC
393
        imh, imw = im.shape[:2]
394
        m = min(imh, imw)  # min dimension
395
        top, left = (imh - m) // 2, (imw - m) // 2
396
        return cv2.resize(im[top:top + m, left:left + m], (self.w, self.h), interpolation=cv2.INTER_LINEAR)
397
398
399
class ToTensor:
400
    # YOLOv5 ToTensor class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])
401
    def __init__(self, half=False):
402
        super().__init__()
403
        self.half = half
404
405
    def __call__(self, im):  # im = np.array HWC in BGR order
406
        im = np.ascontiguousarray(im.transpose((2, 0, 1))[::-1])  # HWC to CHW -> BGR to RGB -> contiguous
407
        im = torch.from_numpy(im)  # to torch
408
        im = im.half() if self.half else im.float()  # uint8 to fp16/32
409
        im /= 255.0  # 0-255 to 0.0-1.0
410
        return im