yolov5 优化——mosaic相关

这篇具有很好参考价值的文章主要介绍了yolov5 优化——mosaic相关。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

概述

Mosaic 利用了四张图片重新排布成一张图片,根据论文所说其拥有一个巨大的优点是丰富检测物体的背景:随机缩放增加了很多小目标,让网络的鲁棒性更好;且在BN计算的时候一下子会计算四张图片的数据!但是,同时:如果我们的数据集本身就有很多的小目标,那么Mosaic数据增强会导致本来较小的目标变得更小,导致模型的泛化能力变差。如果我们的类目的关键信息是框的某个局部(某些场景你又不能标局部)那么裁切可能会将这个局部信息裁切没,导致模型无法拟合真正的信息。

实现:

原理和实现可以参考这篇链接睿智的目标检测28——YoloV4当中的Mosaic数据增强方法_Bubbliiiing的博客-CSDN博客_mosaic方法,里面主要是yoloV4 的。但是,yolov5 并没有按部就班、原封不动的使用这种实现。它的实现伪代码是(本文针对3.1版本,看了6.1虽然代码结构变了,实现的核心代码并没有改变):

1、针对当前一张图,从该epoch内已训练过的图中随机抽取3张图。同时生成一张4倍模型输入大小的背景图(用于将后面四张图贴上去)

2、针对当前图进行等比缩放(最长边等于模型预设输入尺寸,如640)。将当前图随机上下左右平移(+— 1/2模型输入图尺寸,其中1/2居然是写死的,且牵扯到了后面其他函数)。

3、将随机抽取的3张图也进行等比缩放(最长边等于模型预设输入尺寸,如640),然后根据当前图的位置,进行依次放在左边,下边、右下。

至此mosaic 完成,然后通过对生成的4倍大小的图整体进行二次的HSV、旋转、透视变换(这里缩放回原来的预设模型尺寸)、mixup等操作。

可以看出来生成的图已经比较不鲁棒了,这里感觉到了学术闭集刷性能(确实精召都提高了),和工业界大多开集上,这种训练出来的模型,fpr很难压下去(明显模型已经学错了)。所以工业界还是慎用,或者自己按需修改mosaic的超参或者实现。

yolov5 优化——mosaic相关

涉及到的源码如下:

1、配置文件

yolov5/hyp.finetune.yaml at v3.1 · ultralytics/yolov5 · GitHub

yolov5 优化——mosaic相关

2、源码这两个部分也需要按需修改强度

https://github.com/ultralytics/yolov5/blob/v3.1/utils/datasets.py

yolov5 优化——mosaic相关

yolov5 优化——mosaic相关

源码实现mosaic的主代码如下文章来源地址https://www.toymoban.com/news/detail-484544.html

def load_mosaic(self, index):
    # loads images in a mosaic

    labels4 = []
    s = self.img_size
    yc, xc  = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border]  # mosaic center x, y
    indices = [index] + [random.randint(0, len(self.labels) - 1) for _ in range(3)]  # 3 additional image indices
    for i, index in enumerate(indices):
        # Load image
        img, _, (h, w) = load_image(self, index)

        # place img in img4
        if i == 0:  # top left
            img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8)  # base image with 4 tiles
            x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc  # xmin, ymin, xmax, ymax (large image)
            x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h  # xmin, ymin, xmax, ymax (small image)
        elif i == 1:  # top right
            x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
            x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
        elif i == 2:  # bottom left
            x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
            x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
        elif i == 3:  # bottom right
            x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
            x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)

        img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b]  # img4[ymin:ymax, xmin:xmax]
        padw = x1a - x1b
        padh = y1a - y1b

        # Labels
        x = self.labels[index]
        labels = x.copy()
        if x.size > 0:  # Normalized xywh to pixel xyxy format
            labels[:, 1] = w * (x[:, 1] - x[:, 3] / 2) + padw
            labels[:, 2] = h * (x[:, 2] - x[:, 4] / 2) + padh
            labels[:, 3] = w * (x[:, 1] + x[:, 3] / 2) + padw
            labels[:, 4] = h * (x[:, 2] + x[:, 4] / 2) + padh
        labels4.append(labels)
#     print('img4', img4.shape)
    # Concat/clip labels
    if len(labels4):
        labels4 = np.concatenate(labels4, 0)
        np.clip(labels4[:, 1:], 0, 2 * s, out=labels4[:, 1:])  # use with random_perspective
        # img4, labels4 = replicate(img4, labels4)  # replicate

    # Augment
    img4, labels4 = random_perspective(img4, labels4,
                                       degrees=self.hyp['degrees'],
                                       translate=self.hyp['translate'],
                                       scale=self.hyp['scale'],
                                       shear=self.hyp['shear'],
                                       perspective=self.hyp['perspective'],
                                       border=self.mosaic_border)  # border to remove

    return img4, labels4
def load_image(self, index):
    # loads 1 image from dataset, returns img, original hw, resized hw
    img = self.imgs[index]
    if img is None:  # not cached
        path = self.img_files[index]
        img = cv2.imread(path)  # BGR
        assert img is not None, 'Image Not Found ' + path
        h0, w0 = img.shape[:2]  # orig hw
        r = self.img_size / max(h0, w0)  # resize image to img_size
        if r != 1:  # always resize down, only resize up if training with augmentation
            interp = cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR
            img = cv2.resize(img, (int(w0 * r), int(h0 * r)), interpolation=interp)
        return img, (h0, w0), img.shape[:2]  # img, hw_original, hw_resized
    else:
        return self.imgs[index], self.img_hw0[index], self.img_hw[index]  # img, hw_original, hw_resized
def random_perspective(img, targets=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0, border=(0, 0)):
    # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
    # targets = [cls, xyxy]

#     height = img.shape[0] + border[0] * 2  # shape(h,w,c)
#     width = img.shape[1] + border[1] * 2
    if border==(0, 0): # 不使用mosaic
        height = img.shape[0] # shape(h,w,c)
        width = img.shape[1]
    else: # 使用mosaic, 先将图片扩展为2倍,所以需要回归到原始大小
        height = img.shape[0]// 2 # shape(h,w,c)
        width = img.shape[1] // 2
    

    # Center
    C = np.eye(3)
    C[0, 2] = -img.shape[1] / 2  # x translation (pixels)
    C[1, 2] = -img.shape[0] / 2  # y translation (pixels)

    # Perspective
    P = np.eye(3)
    P[2, 0] = random.uniform(-perspective, perspective)  # x perspective (about y)
    P[2, 1] = random.uniform(-perspective, perspective)  # y perspective (about x)

    # Rotation and Scale
    R = np.eye(3)
    a = random.uniform(-degrees, degrees)
    # a += random.choice([-180, -90, 0, 90])  # add 90deg rotations to small rotations
    s = random.uniform(1 - scale, 1 + scale)
    # s = 2 ** random.uniform(-scale, scale)
    R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)

    # Shear
    S = np.eye(3)
    S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180)  # x shear (deg)
    S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180)  # y shear (deg)

    # Translation
    T = np.eye(3)
    T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width  # x translation (pixels)
    T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height  # y translation (pixels)

    # Combined rotation matrix
    M = T @ S @ R @ P @ C  # order of operations (right to left) is IMPORTANT
    if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any():  # image changed
        if perspective:
            img = cv2.warpPerspective(img, M, dsize=(width, height), borderValue=(114, 114, 114))
        else:  # affine
            img = cv2.warpAffine(img, M[:2], dsize=(width, height), borderValue=(114, 114, 114))

    # Visualize
    # import matplotlib.pyplot as plt
    # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
    # ax[0].imshow(img[:, :, ::-1])  # base
    # ax[1].imshow(img2[:, :, ::-1])  # warped

    # Transform label coordinates
    n = len(targets)
    if n:
        # warp points
        xy = np.ones((n * 4, 3))
        xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2)  # x1y1, x2y2, x1y2, x2y1
        xy = xy @ M.T  # transform
        if perspective:
            xy = (xy[:, :2] / xy[:, 2:3]).reshape(n, 8)  # rescale
        else:  # affine
            xy = xy[:, :2].reshape(n, 8)

        # create new boxes
        x = xy[:, [0, 2, 4, 6]]
        y = xy[:, [1, 3, 5, 7]]
        xy = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T

        # # apply angle-based reduction of bounding boxes
        # radians = a * math.pi / 180
        # reduction = max(abs(math.sin(radians)), abs(math.cos(radians))) ** 0.5
        # x = (xy[:, 2] + xy[:, 0]) / 2
        # y = (xy[:, 3] + xy[:, 1]) / 2
        # w = (xy[:, 2] - xy[:, 0]) * reduction
        # h = (xy[:, 3] - xy[:, 1]) * reduction
        # xy = np.concatenate((x - w / 2, y - h / 2, x + w / 2, y + h / 2)).reshape(4, n).T

        # clip boxes
        xy[:, [0, 2]] = xy[:, [0, 2]].clip(0, width)
        xy[:, [1, 3]] = xy[:, [1, 3]].clip(0, height)

        # filter candidates
        i = box_candidates(box1=targets[:, 1:5].T * s, box2=xy.T)
        targets = targets[i]
        targets[:, 1:5] = xy[i]

    return img, targets
def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):
    r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1  # random gains
    hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
    dtype = img.dtype  # uint8

    x = np.arange(0, 256, dtype=np.int16)
    lut_hue = ((x * r[0]) % 180).astype(dtype)
    lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
    lut_val = np.clip(x * r[2], 0, 255).astype(dtype)

    img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))).astype(dtype)
    cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img)  # no return needed

    # Histogram equalization
    # if random.random() < 0.2:
    #     for i in range(3):
    #         img[:, :, i] = cv2.equalizeHist(img[:, :, i])

到了这里,关于yolov5 优化——mosaic相关的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 目标检测常见数据增强算法汇总讲解(Mixup,Cutout,CutMix,Mosaic)

           在学习目标检测算法的过程中,发现了一些有趣的目标检测算法,打算简单写个笔记,不足之处还望谅解,可以在评论中指出来。         目标检测作为需要大量数据的算法,在实际情况中经常面临数据不足的情况,事实上很多时候数据确实对于开发者来说非常难搞

    2024年02月04日
    浏览(34)
  • 【Yolov5】Yolov5添加ASFF, 网络改进优化

    🚀🚀🚀 Yolov5添加ASFF 🚀🚀🚀 Yolov5是单阶段目标检测算法的一种,网上有很多改进其性能的方法,添加ASFF模块就是其中一种,但是ASFF本身是用于Yolov3的,在v5中无法直接应用,且网上许多博客都是介绍这个模块的原理,没有直接可以应用的代码程序,我这里提供一种方案

    2023年04月08日
    浏览(39)
  • YOLOv5基础知识入门(3)— 目标检测相关知识点

      前言 : Hello大家好,我是小哥谈。 YOLO算法发展历程和YOLOv5核心基础知识学习完成之后,接下来我们就需要学习目标检测相关知识了。为了让大家后面可以顺利地用YOLOv5进行目标检测实战,本节课就带领大家学习一下目标检测的基础知识点,希望大家学习之后有所收获!

    2024年02月13日
    浏览(27)
  • Ubuntu20.04配置YOLOV5算法相关环境,并运行融合YOLOV5的ORB-SLAM2开源代码(亲测有效)

              这篇博客介绍的是如何在Ubuntu系统下配置YOLOV5算法环境。并且运行一个融合YOLOV5的ORB-SLAM2开源代码。         安装的软件主要是anaconda,然后anaconda可以帮我们安装python、pytorch这些东西。我的ubuntu版本:ubuntu20.04.5LTS。 安装的anaconda类型: Anaconda3-2022.05 安装的p

    2024年02月02日
    浏览(37)
  • YOLOv5-优化器和学习率调整策略

    pytorch-优化器和学习率调整 这个链接关于优化器和学习率的一些基础讲得很细,还有相关实现代码 前向传播的过程,会得到模型输出与真实标签的差,我们称之为损失, 有了损失,我们会进入反向传播过程得到参数的梯度,接下来就是优化器干活, 优化器( 梯度下降 )要

    2024年02月03日
    浏览(33)
  • 从R-CNN到Faster-RCNN再到YOLOV5,目标检测网络发展概述

     R-CNN由Ross Girshick于2014年提出,R-CNN首先通过 选择性搜索算法Selective Search 从一组对象候选框中选择可能出现的对象框,然后将这些选择出来的对象框中的图像resize到某一固定尺寸的图像,并喂入到 CNN模型 (经过在ImageNet数据集上训练过的CNN模型,如AlexNet)提取特征,最后将

    2024年02月05日
    浏览(49)
  • 探索YOLOv5微服务:gRPC Proto设计与优化策略

    YOLOv5(You Only Look Once, version 5)是一种流行的深度学习模型,用于实时对象检测。作为YOLO系列的最新迭代,它以其高效的性能和相对较低的资源需求而闻名。YOLOv5的核心优势在于其能够在单次前向传递中同时预测多个对象的类别和位置,这使得它在实时图像处理和视频分析领

    2024年01月21日
    浏览(31)
  • 优化改进YOLOv5算法之Wise-IOU损失函数

    边界框回归(BBR)的损失函数对于目标检测至关重要。它的良好定义将为模型带来显著的性能改进。大多数现有的工作假设训练数据中的样本是高质量的,并侧重于增强BBR损失的拟合能力。如果盲目地加强低质量样本的BBR,这将危及本地化性能。Focal EIoU v1被提出来解决这个问

    2024年01月17日
    浏览(40)
  • yolov5 优化方法(四)修改bbox损失函数(补充EIOU,SIOU)

    【参考文档】江大白的yolo解析 后面会给出我的完整代码,先来分段看看! 转换成这种格式: 这个应该都很熟了 clamp inf:无穷大 -inf:负无穷 out:输出,默认即可,不用设定 在 yolov5的使用中,应该是截断掉小于0的部分 torch.clamp 在正式进入各种iou之前 cw :最小外包矩形宽度

    2024年02月06日
    浏览(39)
  • 改进YOLO系列 | YOLOv5/v7 引入谷歌 Lion 优化器

    论文地址:https://arxiv.org/pdf/2302.06675.pdf 代码地址:https://github.com/google/automl/tree/master/lion 我们提出了一种将算法发现作为程序搜索的方法,并将其应用于发现用于深度神经网络训练的优化算法。我们利用高效的搜索技术来探索一个无限且稀疏的程序空间。为了弥补代理任务和

    2024年02月09日
    浏览(25)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包