CoolFace
Apppublic

Bai360/Cotton2

sourceHugging Faceopenrailupdated 3y agoView on Hugging Face
0likes
augmentations.py398 linesDownload Raw Back to utils
1# YOLOv5 ๐Ÿš€ by Ultralytics, GPL-3.0 license2"""3Image augmentation functions4"""5 6import math7import random8 9import cv210import numpy as np11import torch12import torchvision.transforms as T13import torchvision.transforms.functional as TF14 15from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box, xywhn2xyxy16from utils.metrics import bbox_ioa17 18IMAGENET_MEAN = 0.485, 0.456, 0.406  # RGB mean19IMAGENET_STD = 0.229, 0.224, 0.225  # RGB standard deviation20 21 22class Albumentations:23    # YOLOv5 Albumentations class (optional, only used if package is installed)24    def __init__(self, size=640):25        self.transform = None26        prefix = colorstr('albumentations: ')27        try:28            import albumentations as A29            check_version(A.__version__, '1.0.3', hard=True)  # version requirement30 31            T = [32                A.RandomResizedCrop(height=size, width=size, scale=(0.8, 1.0), ratio=(0.9, 1.11), p=0.0),33                A.Blur(p=0.01),34                A.MedianBlur(p=0.01),35                A.ToGray(p=0.01),36                A.CLAHE(p=0.01),37                A.RandomBrightnessContrast(p=0.0),38                A.RandomGamma(p=0.0),39                A.ImageCompression(quality_lower=75, p=0.0)]  # transforms40            self.transform = A.Compose(T, bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))41 42            LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))43        except ImportError:  # package not installed, skip44            pass45        except Exception as e:46            LOGGER.info(f'{prefix}{e}')47 48    def __call__(self, im, labels, p=1.0):49        if self.transform and random.random() < p:50            new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0])  # transformed51            im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])])52        return im, labels53 54 55def normalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD, inplace=False):56    # Denormalize RGB images x per ImageNet stats in BCHW format, i.e. = (x - mean) / std57    return TF.normalize(x, mean, std, inplace=inplace)58 59 60def denormalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD):61    # Denormalize RGB images x per ImageNet stats in BCHW format, i.e. = x * std + mean62    for i in range(3):63        x[:, i] = x[:, i] * std[i] + mean[i]64    return x65 66 67def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):68    # HSV color-space augmentation69    if hgain or sgain or vgain:70        r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1  # random gains71        hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV))72        dtype = im.dtype  # uint873 74        x = np.arange(0, 256, dtype=r.dtype)75        lut_hue = ((x * r[0]) % 180).astype(dtype)76        lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)77        lut_val = np.clip(x * r[2], 0, 255).astype(dtype)78 79        im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))80        cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im)  # no return needed81 82 83def hist_equalize(im, clahe=True, bgr=False):84    # Equalize histogram on BGR image 'im' with im.shape(n,m,3) and range 0-25585    yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)86    if clahe:87        c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))88        yuv[:, :, 0] = c.apply(yuv[:, :, 0])89    else:90        yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0])  # equalize Y channel histogram91    return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB)  # convert YUV image to RGB92 93 94def replicate(im, labels):95    # Replicate labels96    h, w = im.shape[:2]97    boxes = labels[:, 1:].astype(int)98    x1, y1, x2, y2 = boxes.T99    s = ((x2 - x1) + (y2 - y1)) / 2  # side length (pixels)100    for i in s.argsort()[:round(s.size * 0.5)]:  # smallest indices101        x1b, y1b, x2b, y2b = boxes[i]102        bh, bw = y2b - y1b, x2b - x1b103        yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw))  # offset x, y104        x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]105        im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b]  # im4[ymin:ymax, xmin:xmax]106        labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)107 108    return im, labels109 110 111def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):112    # Resize and pad image while meeting stride-multiple constraints113    shape = im.shape[:2]  # current shape [height, width]114    if isinstance(new_shape, int):115        new_shape = (new_shape, new_shape)116 117    # Scale ratio (new / old)118    r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])119    if not scaleup:  # only scale down, do not scale up (for better val mAP)120        r = min(r, 1.0)121 122    # Compute padding123    ratio = r, r  # width, height ratios124    new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))125    dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding126    if auto:  # minimum rectangle127        dw, dh = np.mod(dw, stride), np.mod(dh, stride)  # wh padding128    elif scaleFill:  # stretch129        dw, dh = 0.0, 0.0130        new_unpad = (new_shape[1], new_shape[0])131        ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios132 133    dw /= 2  # divide padding into 2 sides134    dh /= 2135 136    if shape[::-1] != new_unpad:  # resize137        im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)138    top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))139    left, right = int(round(dw - 0.1)), int(round(dw + 0.1))140    im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)  # add border141    return im, ratio, (dw, dh)142 143 144def random_perspective(im,145                       targets=(),146                       segments=(),147                       degrees=10,148                       translate=.1,149                       scale=.1,150                       shear=10,151                       perspective=0.0,152                       border=(0, 0)):153    # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10))154    # targets = [cls, xyxy]155 156    height = im.shape[0] + border[0] * 2  # shape(h,w,c)157    width = im.shape[1] + border[1] * 2158 159    # Center160    C = np.eye(3)161    C[0, 2] = -im.shape[1] / 2  # x translation (pixels)162    C[1, 2] = -im.shape[0] / 2  # y translation (pixels)163 164    # Perspective165    P = np.eye(3)166    P[2, 0] = random.uniform(-perspective, perspective)  # x perspective (about y)167    P[2, 1] = random.uniform(-perspective, perspective)  # y perspective (about x)168 169    # Rotation and Scale170    R = np.eye(3)171    a = random.uniform(-degrees, degrees)172    # a += random.choice([-180, -90, 0, 90])  # add 90deg rotations to small rotations173    s = random.uniform(1 - scale, 1 + scale)174    # s = 2 ** random.uniform(-scale, scale)175    R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)176 177    # Shear178    S = np.eye(3)179    S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180)  # x shear (deg)180    S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180)  # y shear (deg)181 182    # Translation183    T = np.eye(3)184    T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width  # x translation (pixels)185    T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height  # y translation (pixels)186 187    # Combined rotation matrix188    M = T @ S @ R @ P @ C  # order of operations (right to left) is IMPORTANT189    if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any():  # image changed190        if perspective:191            im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))192        else:  # affine193            im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))194 195    # Visualize196    # import matplotlib.pyplot as plt197    # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()198    # ax[0].imshow(im[:, :, ::-1])  # base199    # ax[1].imshow(im2[:, :, ::-1])  # warped200 201    # Transform label coordinates202    n = len(targets)203    if n:204        use_segments = any(x.any() for x in segments)205        new = np.zeros((n, 4))206        if use_segments:  # warp segments207            segments = resample_segments(segments)  # upsample208            for i, segment in enumerate(segments):209                xy = np.ones((len(segment), 3))210                xy[:, :2] = segment211                xy = xy @ M.T  # transform212                xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]  # perspective rescale or affine213 214                # clip215                new[i] = segment2box(xy, width, height)216 217        else:  # warp boxes218            xy = np.ones((n * 4, 3))219            xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2)  # x1y1, x2y2, x1y2, x2y1220            xy = xy @ M.T  # transform221            xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8)  # perspective rescale or affine222 223            # create new boxes224            x = xy[:, [0, 2, 4, 6]]225            y = xy[:, [1, 3, 5, 7]]226            new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T227 228            # clip229            new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)230            new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)231 232        # filter candidates233        i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)234        targets = targets[i]235        targets[:, 1:5] = new[i]236 237    return im, targets238 239 240def copy_paste(im, labels, segments, p=0.5):241    # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)242    n = len(segments)243    if p and n:244        h, w, c = im.shape  # height, width, channels245        im_new = np.zeros(im.shape, np.uint8)246        for j in random.sample(range(n), k=round(p * n)):247            l, s = labels[j], segments[j]248            box = w - l[3], l[2], w - l[1], l[4]249            ioa = bbox_ioa(box, labels[:, 1:5])  # intersection over area250            if (ioa < 0.30).all():  # allow 30% obscuration of existing labels251                labels = np.concatenate((labels, [[l[0], *box]]), 0)252                segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))253                cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (1, 1, 1), cv2.FILLED)254 255        result = cv2.flip(im, 1)  # augment segments (flip left-right)256        i = cv2.flip(im_new, 1).astype(bool)257        im[i] = result[i]  # cv2.imwrite('debug.jpg', im)  # debug258 259    return im, labels, segments260 261 262def cutout(im, labels, p=0.5):263    # Applies image cutout augmentation https://arxiv.org/abs/1708.04552264    if random.random() < p:265        h, w = im.shape[:2]266        scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16  # image size fraction267        for s in scales:268            mask_h = random.randint(1, int(h * s))  # create random masks269            mask_w = random.randint(1, int(w * s))270 271            # box272            xmin = max(0, random.randint(0, w) - mask_w // 2)273            ymin = max(0, random.randint(0, h) - mask_h // 2)274            xmax = min(w, xmin + mask_w)275            ymax = min(h, ymin + mask_h)276 277            # apply random color mask278            im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]279 280            # return unobscured labels281            if len(labels) and s > 0.03:282                box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)283                ioa = bbox_ioa(box, xywhn2xyxy(labels[:, 1:5], w, h))  # intersection over area284                labels = labels[ioa < 0.60]  # remove >60% obscured labels285 286    return labels287 288 289def mixup(im, labels, im2, labels2):290    # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf291    r = np.random.beta(32.0, 32.0)  # mixup ratio, alpha=beta=32.0292    im = (im * r + im2 * (1 - r)).astype(np.uint8)293    labels = np.concatenate((labels, labels2), 0)294    return im, labels295 296 297def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16):  # box1(4,n), box2(4,n)298    # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio299    w1, h1 = box1[2] - box1[0], box1[3] - box1[1]300    w2, h2 = box2[2] - box2[0], box2[3] - box2[1]301    ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps))  # aspect ratio302    return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr)  # candidates303 304 305def classify_albumentations(306        augment=True,307        size=224,308        scale=(0.08, 1.0),309        ratio=(0.75, 1.0 / 0.75),  # 0.75, 1.33310        hflip=0.5,311        vflip=0.0,312        jitter=0.4,313        mean=IMAGENET_MEAN,314        std=IMAGENET_STD,315        auto_aug=False):316    # YOLOv5 classification Albumentations (optional, only used if package is installed)317    prefix = colorstr('albumentations: ')318    try:319        import albumentations as A320        from albumentations.pytorch import ToTensorV2321        check_version(A.__version__, '1.0.3', hard=True)  # version requirement322        if augment:  # Resize and crop323            T = [A.RandomResizedCrop(height=size, width=size, scale=scale, ratio=ratio)]324            if auto_aug:325                # TODO: implement AugMix, AutoAug & RandAug in albumentation326                LOGGER.info(f'{prefix}auto augmentations are currently not supported')327            else:328                if hflip > 0:329                    T += [A.HorizontalFlip(p=hflip)]330                if vflip > 0:331                    T += [A.VerticalFlip(p=vflip)]332                if jitter > 0:333                    color_jitter = (float(jitter),) * 3  # repeat value for brightness, contrast, satuaration, 0 hue334                    T += [A.ColorJitter(*color_jitter, 0)]335        else:  # Use fixed crop for eval set (reproducibility)336            T = [A.SmallestMaxSize(max_size=size), A.CenterCrop(height=size, width=size)]337        T += [A.Normalize(mean=mean, std=std), ToTensorV2()]  # Normalize and convert to Tensor338        LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))339        return A.Compose(T)340 341    except ImportError:  # package not installed, skip342        LOGGER.warning(f'{prefix}โš ๏ธ not found, install with `pip install albumentations` (recommended)')343    except Exception as e:344        LOGGER.info(f'{prefix}{e}')345 346 347def classify_transforms(size=224):348    # Transforms to apply if albumentations not installed349    assert isinstance(size, int), f'ERROR: classify_transforms size {size} must be integer, not (list, tuple)'350    # T.Compose([T.ToTensor(), T.Resize(size), T.CenterCrop(size), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])351    return T.Compose([CenterCrop(size), ToTensor(), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])352 353 354class LetterBox:355    # YOLOv5 LetterBox class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])356    def __init__(self, size=(640, 640), auto=False, stride=32):357        super().__init__()358        self.h, self.w = (size, size) if isinstance(size, int) else size359        self.auto = auto  # pass max size integer, automatically solve for short side using stride360        self.stride = stride  # used with auto361 362    def __call__(self, im):  # im = np.array HWC363        imh, imw = im.shape[:2]364        r = min(self.h / imh, self.w / imw)  # ratio of new/old365        h, w = round(imh * r), round(imw * r)  # resized image366        hs, ws = (math.ceil(x / self.stride) * self.stride for x in (h, w)) if self.auto else self.h, self.w367        top, left = round((hs - h) / 2 - 0.1), round((ws - w) / 2 - 0.1)368        im_out = np.full((self.h, self.w, 3), 114, dtype=im.dtype)369        im_out[top:top + h, left:left + w] = cv2.resize(im, (w, h), interpolation=cv2.INTER_LINEAR)370        return im_out371 372 373class CenterCrop:374    # YOLOv5 CenterCrop class for image preprocessing, i.e. T.Compose([CenterCrop(size), ToTensor()])375    def __init__(self, size=640):376        super().__init__()377        self.h, self.w = (size, size) if isinstance(size, int) else size378 379    def __call__(self, im):  # im = np.array HWC380        imh, imw = im.shape[:2]381        m = min(imh, imw)  # min dimension382        top, left = (imh - m) // 2, (imw - m) // 2383        return cv2.resize(im[top:top + m, left:left + m], (self.w, self.h), interpolation=cv2.INTER_LINEAR)384 385 386class ToTensor:387    # YOLOv5 ToTensor class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])388    def __init__(self, half=False):389        super().__init__()390        self.half = half391 392    def __call__(self, im):  # im = np.array HWC in BGR order393        im = np.ascontiguousarray(im.transpose((2, 0, 1))[::-1])  # HWC to CHW -> BGR to RGB -> contiguous394        im = torch.from_numpy(im)  # to torch395        im = im.half() if self.half else im.float()  # uint8 to fp16/32396        im /= 255.0  # 0-255 to 0.0-1.0397        return im398