1、前言

本文主要使用YOLOv8的C2F模块替换YOLOv5中的C3模块,经过实验测试,发现YOLOv5更加适合嵌入式设备,所以并不是越新的框架性能就会越好。通常大部分的目标检测模型都是在coco数据集上进行训练,然后再与旧的模型进行比较,如果只看在coco数据集上的表现确实v7、v8是要优于v5的,但是在自己数据集上面训练可能就是另外一种结果,所以可以尝试将不同模型的不同模块进行融合,试一试训练效果。

2、C3模块和C2F模块

2.1、C3模块

YOLOV5 采用C3模块,类似于残差结构的思想,C3模块由三个CBS模块,也就是三个卷积层,再加上若干个BottleNeck模块构成,输入进来的特征,分为两个部分,一部分特征是只经过CBS模块处理,一部分经过CBS+BottleNeck处理,最后通过concat将两部分特征进行拼接,再经过一个CBS层将特征维度进行恢复。

class C3(nn.Module):
    # CSP Bottleneck with 3 convolutions
    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, number, shortcut, groups, expansion
        super().__init__()
        c_ = int(c2 * e)  # hidden channels
        self.cv1 = Conv(c1, c_, 1, 1)
        self.cv2 = Conv(c1, c_, 1, 1)
        self.cv3 = Conv(2 * c_, c2, 1)  # optional act=FReLU(c2)
        self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
 
    def forward(self, x):
        return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))

YOLOv5-v6.0版本中使用了C3模块,替代了早期的BottleneckCSP模块。这两者结构作用基本相同,均为CSP架构,只是在修正单元的选择上有所不同,C3模块包含了3个标准卷积层以及多个Bottleneck模块,与BottleneckCSP模块所不同的是,C3经过Bottleneck模块输出后的Conv模块被去掉了。旧版本的yolov5的CSP模块如下:

2.2、BottleNeck模块

BottleNeck模块是类似与resnet残差结构,该模块其实存在两种形式,也就是BottleNeck1和BottleNeck2,BottleNeck1是以resnet残差结构连接的,该残差结构是由两条路构成,其中一路先进行1×1卷积将特征图的通道数减小一半,从而减少计算量,再通过3×3卷积提取特征,并且将通道数加倍,其输入与输出的通道数是不发生改变的,而另外一路通过shortcut进行残差连接,与第一路的输出特征图相加,从而实现特征融合;BottleNeck2只是经过一次1x1卷积的CBS和一次3x3卷积的CBS

2.3、C2F模块

CBS处理之后的特征首先进行Split分割成两部分特征,一部分特征保留不做任何处理,一部分经过若干个BottleNeck进行处理;其中每个BottleNeck又会分出两条通道,一条是将处理过的特征传递给下一个BottleNeck,一条则是保留下来用作后面的concat连接。最后经过n个BottleNeck之后将所有的特征进行融合。

n个BottleNeck的特征融合方式很像FPN特征金字塔自顶向下融合,将深层特征与浅层特征进行融合 。

在这里插入图片描述

C2f 使用了3个卷积模块(ConV+BN+SILU),以及n个BottleNeck构成输入的特征经过Split之后通道数变为原来的一半(h ∗ w ∗ 0.5cout),一半的特征图不做处理,另外一半则是传入到BottleNeck模块中做特征融合操作,其结构图如下:

3、C2F代码实现

添加C2f和C2F_Bottleneck模块代码,因为YOLOv5和YOLOv8的Bottleneck模块不一致,这里直接拷贝YOLOv8源码的C2f和C2F_Bottleneck模块。

3.1、common.py

models/common.py的加入C2fC2F_Bottleneck

class C2f(nn.Module):
    """Faster Implementation of CSP Bottleneck with 2 convolutions."""

    def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5):
        """Initialize CSP bottleneck layer with two convolutions with arguments ch_in, ch_out, number, shortcut, groups,
        expansion.
        """
        super().__init__()
        self.c = int(c2 * e)  # hidden channels
        self.cv1 = Conv(c1, 2 * self.c, 1, 1)
        self.cv2 = Conv((2 + n) * self.c, c2, 1)  # optional act=FReLU(c2)
        self.m = nn.ModuleList(C2F_Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n))

    def forward(self, x):
        """Forward pass through C2f layer."""
        y = list(self.cv1(x).chunk(2, 1))
        y.extend(m(y[-1]) for m in self.m)
        return self.cv2(torch.cat(y, 1))

    def forward_split(self, x):
        """Forward pass using split() instead of chunk()."""
        y = list(self.cv1(x).split((self.c, self.c), 1))
        y.extend(m(y[-1]) for m in self.m)
        return self.cv2(torch.cat(y, 1))


class C2F_Bottleneck(nn.Module):
    """Standard bottleneck."""

    def __init__(self, c1, c2, shortcut=True, g=1, k=(3, 3), e=0.5):
        """Initializes a bottleneck module with given input/output channels, shortcut option, group, kernels, and
        expansion.
        """
        super().__init__()
        c_ = int(c2 * e)  # hidden channels
        self.cv1 = Conv(c1, c_, k[0], 1)
        self.cv2 = Conv(c_, c2, k[1], 1, g=g)
        self.add = shortcut and c1 == c2

    def forward(self, x):
        """'forward()' applies the YOLO FPN to input data."""
        return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))

3.2、yolo.py

models/yolo.py的parse_model函数,添加C2f 模块

if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP,C3, C2f]:

在这里插入图片描述

3.3、yolov5s_C2F.yaml

models文件夹新建一个yolov5s_C2F.yaml文件,将yolov5s所有的C3模块都换成了C2f模块。

# YOLOv5 🚀 by Ultralytics, GPL-3.0 license

# Parameters
nc: 6  # number of classes
depth_multiple: 0.33  # model depth multiple
width_multiple: 0.50  # layer channel multiple
anchors:
  - [ 10,13, 16,30, 33,23 ]  # P3/8
  - [ 30,61, 62,45, 59,119 ]  # P4/16
  - [ 116,90, 156,198, 373,326 ]  # P5/32

# YOLOv5 v6.0 backbone
backbone:
  # [from, number, module, args] 输出640*640
  [ [ -1, 1, Conv, [ 64, 6, 2, 2 ] ],  # 0-P1/2 320*320    64表示输出的channel,但是需要乘以width_multiple,6表示卷积核的大小,2表示padding大小,2表示stride大小
    [ -1, 1, Conv, [ 128, 3, 2 ] ],  # 1-P2/4   160*160*128      2表示stride大小
    [ -1, 3, C2f, [ 128 ] ],
    [ -1, 1, Conv, [ 256, 3, 2 ] ],  # 3-P3/8   80*80*256
    [ -1, 6, C2f, [ 256 ] ],
    [ -1, 1, Conv, [ 512, 3, 2 ] ],  # 5-P4/16   40*40*512
    [ -1, 9, C2f, [ 512 ] ],
    [ -1, 1, Conv, [ 1024, 3, 2 ] ],  # 7-P5/32   20*20
    [ -1, 3, C2f, [ 1024 ] ],
    [ -1, 1, SPPF, [ 1024, 5 ] ],  # 9
  ]

# YOLOv5 v6.0 head
head:
  #  ================ 自下向上融合FPN =====================
  [ [ -1, 1, Conv, [ 512, 1, 1 ] ], # 降维 20*20*1024->20*20*512
    [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], #上采样 20*20*512->40*40*512
    [ [ -1, 6 ], 1, Concat, [ 1 ] ],  # cat backbone P4 40*40*(512+512)
    [ -1, 3, C2f, [ 512, False ] ],  # 13             40*40*1024->40*40*512

    [ -1, 1, Conv, [ 256, 1, 1 ] ],         #40*40*512->40*40*256
    [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],   # 40*40*256->80*80*256
    [ [ -1, 4 ], 1, Concat, [ 1 ] ],  # cat backbone P3 80*80*(256+256)
    [ -1, 3, C2f, [ 256, False ] ],  # 17 (P3/8-small) 80*80*512->80*80*256


    # ================ 自上向下融合PAN ==================
    [ -1, 1, Conv, [ 256, 3, 2 ] ],  # 80*80*256->40*40*256
    [ [ -1, 14 ], 1, Concat, [ 1 ] ],  # cat head P4  40*40*(256+256)
    [ -1, 3, C2f, [ 512, False ] ],  # 20 (P4/16-medium)

    [ -1, 1, Conv, [ 512, 3, 2 ] ],   #40*40*(256+256)-> 20*20*512
    [ [ -1, 10 ], 1, Concat, [ 1 ] ],  # cat head P5  20*20*(512+512)
    [ -1, 3, C2f, [ 1024, False ] ],  # 23 (P5/32-large)

    [ [ 17, 20, 23 ], 1, Detect, [ nc, anchors ] ],  # Detect(P3, P4, P5)
  ]

4、目标检测系列文章

  1. YOLOv5s网络模型讲解(一看就会)
  2. 生活垃圾数据集(YOLO版)
  3. YOLOv5如何训练自己的数据集
  4. 双向控制舵机(树莓派版)
  5. 树莓派部署YOLOv5目标检测(详细篇)
  6. YOLO_Tracking 实践 (环境搭建 & 案例测试)
  7. 目标检测:数据集划分 & XML数据集转YOLO标签
  8. DeepSort行人车辆识别系统(实现目标检测+跟踪+统计)
  9. YOLOv5参数大全(parse_opt篇)
  10. YOLOv5改进(一)-- 轻量化YOLOv5s模型
  11. YOLOv5改进(二)-- 目标检测优化点(添加小目标头检测)
  12. YOLOv5改进(三)-- 引进Focaler-IoU损失函数
  13. YOLOv5改进(四)–轻量化模型ShuffleNetv2
  14. YOLOv5改进(五)-- 轻量化模型MobileNetv3
GitHub 加速计划 / yo / yolov5
49.31 K
16.02 K
下载
yolov5 - Ultralytics YOLOv8的前身,是一个用于目标检测、图像分割和图像分类任务的先进模型。
最近提交(Master分支:1 个月前 )
b163ff8d * fix: requirements.txt to reduce vulnerabilities The following vulnerabilities are fixed by pinning transitive dependencies: - https://snyk.io/vuln/SNYK-PYTHON-FONTTOOLS-6133203 - https://snyk.io/vuln/SNYK-PYTHON-NUMPY-2321964 - https://snyk.io/vuln/SNYK-PYTHON-NUMPY-2321966 - https://snyk.io/vuln/SNYK-PYTHON-NUMPY-2321970 - https://snyk.io/vuln/SNYK-PYTHON-PILLOW-5918878 - https://snyk.io/vuln/SNYK-PYTHON-PILLOW-6043904 - https://snyk.io/vuln/SNYK-PYTHON-PILLOW-6182918 - https://snyk.io/vuln/SNYK-PYTHON-PILLOW-6219984 - https://snyk.io/vuln/SNYK-PYTHON-PILLOW-6219986 - https://snyk.io/vuln/SNYK-PYTHON-PILLOW-6514866 - https://snyk.io/vuln/SNYK-PYTHON-REQUESTS-6928867 - https://snyk.io/vuln/SNYK-PYTHON-SETUPTOOLS-3180412 - https://snyk.io/vuln/SNYK-PYTHON-SETUPTOOLS-7448482 - https://snyk.io/vuln/SNYK-PYTHON-TORCH-6619806 - https://snyk.io/vuln/SNYK-PYTHON-TORCH-6649934 - https://snyk.io/vuln/SNYK-PYTHON-URLLIB3-7267250 - https://snyk.io/vuln/SNYK-PYTHON-WHEEL-3180413 * Update requirements.txt Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com> --------- Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com> Co-authored-by: snyk-bot <snyk-bot@snyk.io> 14 天前
c5bb4087 * fix: requirements.txt to reduce vulnerabilities The following vulnerabilities are fixed by pinning transitive dependencies: - https://snyk.io/vuln/SNYK-PYTHON-TQDM-6807582 - https://snyk.io/vuln/SNYK-PYTHON-ZIPP-7430899 * Update requirements.txt Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com> --------- Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com> Co-authored-by: snyk-bot <snyk-bot@snyk.io> 14 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐