网站 公司形象,新品发布会的流程,东莞seo整站优化代理,衡水网站建设集团YOLOv5白皮书-第Y4周:common.py文件解读 YOLOv5白皮书-第Y4周:common.py文件解读0.导入需要的包和基本配置1.基本组件1.1 autopad1.2 Conv1.3 Focus1.4 Bottleneck1.5 BottleneckCSP1.6 C31.7 SPP1.8 Concat1.9 Contract、Expand 2.重要类2.1 非极大值抑制#xff08;NMSNMS2.2 AutoShape2.3 Detections2.4 Classify YOLOv5白皮书-第Y4周:common.py文件解读 ) YOLOv5白皮书-第Y4周:common.py文件解读
该文件是实现YOLO算法中各个模块的地方如果我们需要修改某一模块例如C3,那么就需要修改这个文件中对应模块的的定义。由于YOLOV5版本问题同一个模块可能会看到不同的版本这都是正常的以官网为主即可。
本周任务将yolov5s网络模型中的C3模块按照下图方式修改并跑通yolov5。 YOLOv5s网络结构图
0.导入需要的包和基本配置
import ast
import contextlib
import json
import math # 数学函数模块
import platform
import warnings
import zipfile
from collections import OrderedDict, namedtuple
from copy import copy # 数据拷贝模块分浅拷贝和深拷贝
from pathlib import Path # Path将str转换为Path对象使字符串路径易于操作的模块
from urllib.parse import urlparseimport cv2
import numpy as np # numpy数组操作模块
import pandas as pd # pandas数组操作模块
import requests # Python的HTTP客户端库
import torch # pytorch深度学习框架
import torch.nn as nn # 专门为神经网络设计的模块化接口
from IPython.display import display
from PIL import Image # 图像基础操作模块
from torch.cuda import amp # 混合精度训练模块from utils import TryExcept
from utils.dataloaders import exif_transpose, letterbox
from utils.general import (LOGGER, ROOT, Profile, check_requirements, check_suffix, check_version, colorstr,increment_path, is_notebook, make_divisible, non_max_suppression, scale_boxes, xywh2xyxy,xyxy2xywh, yaml_load)
from utils.plots import Annotator, colors, save_one_box
from utils.torch_utils import copy_attr, smart_inference_mode1.基本组件
1.1 autopad
这个模块可以根据输入的卷积核计算卷积模块所需的pad值。将会用于下面会讲到的 Conv 函数和 Classify 函数中。
def autopad(k, pNone, d1): # kernel, padding, dilation# Pad to same shape outputsif d 1:k d * (k - 1) 1 if isinstance(k, int) else [d * (x - 1) 1 for x in k] # actual kernel-sizeif p is None:p k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-padreturn p
1.2 Conv
这个函数是整个网络中最基础的组件由 卷积层 BN层 激活函数 组成具体结构如下
Conv模块代码
class Conv(nn.Module):# Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)default_act nn.SiLU() # default activationdef __init__(self, c1, c2, k1, s1, pNone, g1, d1, actTrue): 在Focus、Bottleneck、BottleneckCSP、C3、SPP、DWConv、TransformerBlock等模块中调用Standard convolution : conv BN act:params c1: 输入的channel值:params c2: 输出的channel值:params k: 卷积的kernel_size:params s: 卷积的stride:params p: 卷积的padding默认是None可以通过autopad自行计算需要的padding值:params g: 卷积的groups数1就是普通的卷积1就是深度可分离卷积:params act: 激活函数类型True就是SiLU()/SwishFalse就是不使用激活函数类型是nn.Module就使用传进来的激活函数类型super().__init__()self.conv nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groupsg, dilationd, biasFalse)self.bn nn.BatchNorm2d(c2)self.act self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()def forward(self, x):return self.act(self.bn(self.conv(x)))def forward_fuse(self, x): 用于Model类的fuse函数融合 Conv BN 加速推理一般用于测试/验证阶段return self.act(self.conv(x))另外这个类中还有一个特殊函数 forward_fuse 这是一个前向加速推理模块在前向传播过程中通过融合 Conv BN 层达到加速推理的作用一般用于测试或验证阶段。
1.3 Focus
为了减少浮点数和提高速度而不是增加featuremap的本质就是将图像进行切片类似于下采样取值将原图像的宽高信息切分聚合到channel通道中。结构如下所示 :# Focus wh information into c-space 把宽度w和高度h的信息整合到c空间中def __init__(self, c1, c2, k1, s1, pNone, g1, actTrue): # ch_in, ch_out, kernel, stride, padding, groups 在yolo.py的parse_model函数中被调用理论从高分辨率图像中周期性的抽出像素点重构到低分辨率图像中即将图像相邻的四个位置进行堆叠聚集wh维度信息到c通道中提高每个点的感受野并减少原始信息的丢失该模块的设计主要是减少计算量加快速度。先做4个slice再concat最后在做Convslice后 (b1,c1,w,h) - 分成4个slice每个slice(b,c1,w/2,h/2)concat(dim1)后 4个slice(b,c1,w/2,h/2) - (b,4c1,w/2,h/2)conv后 (b,4c1,w/2,h/2) - (b,c2,w/2,h/2):params c1: slice后的channel:params c2: Focus最终输出的channel:params k: 最后卷积的kernel:params s: 最后卷积的stride:params p: 最后卷积的padding:params g: 最后卷积的分组情况1普通卷积1深度可分离卷积:params act: bool激活函数类型默认True[SiLU()/Swish]False[不用激活函数] super().__init__()self.conv Conv(c1 * 4, c2, k, s, p, g, actact)# self.contract Contract(gain2)def forward(self, x): # x(b,c,w,h) - y(b,4c,w/2,h/2) 有点像做了个下采样 return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1))# return self.conv(self.contract(x))1.4 Bottleneck
模型结构在这里 class Bottleneck(nn.Module):# Standard bottleneck Conv Conv shortcutdef __init__(self, c1, c2, shortcutTrue, g1, e0.5): # ch_in, ch_out, shortcut, groups, expansion 在BottleneckCSP和yolo.py的parse_model函数中被调用:params c1: 第一个卷积的输入channel:params c2: 第二个卷积的输入channel:params shortcut: bool值是否有shortcut连接默认True:params g: 卷积分组的个数1普通卷积1深度可分离卷积:params e: expansion ratioe*c2就是第一个卷积的输出channel第二个卷积的输入channelsuper().__init__()c_ int(c2 * e) # hidden channelsself.cv1 Conv(c1, c_, 1, 1) # 1x1self.cv2 Conv(c_, c2, 3, 1, gg) # 3x3self.add shortcut and c1 c2 # shortcutTure c1c2 才能做shortcutdef forward(self, x):return x self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
1.5 BottleneckCSP
这个模块是由Bottleneck和CSP结构组成。CSP结构来源于2019年发表的一篇论文CSPNet: A New Backbone that can Enhance Learning Capability of CNN 这个模块和上面yolov5s中的C3模块等效如果要用的话直接在yolov5s.yaml文件中将C3改成BottleneckCSP即可但一般来说不用改因为C3更好。 BottleneckCSP模块具体的结构如下所示 class BottleneckCSP(nn.Module):# CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworksdef __init__(self, c1, c2, n1, shortcutTrue, g1, e0.5): # ch_in, ch_out, number, shortcut, groups, expansion 在C3模块和yolo.py的parse_model函数中被调用:params c1: 整个BottleneckCSP的输入channel:params c2: 整个BottleneckCSP的输出channel:params n: 有n个Bottleneck:params shortcut: bool值Bottleneck中是否有shortcut默认True:params g: Bottleneck中的3x3卷积类型1普通卷积1深度可分离卷积:params e: expansion ratioe*c2中间其它所有层的卷积核个数中间所有层的的输入输出channelsuper().__init__()c_ int(c2 * e) # hidden channelsself.cv1 Conv(c1, c_, 1, 1)self.cv2 nn.Conv2d(c1, c_, 1, 1, biasFalse)self.cv3 nn.Conv2d(c_, c_, 1, 1, biasFalse)self.cv4 Conv(2 * c_, c2, 1, 1)self.bn nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3) 2*c_self.act nn.SiLU()# 叠加n次Bottleneckself.m nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e1.0) for _ in range(n)))def forward(self, x):y1 self.cv3(self.m(self.cv1(x)))y2 self.cv2(x)return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1))))1.6 C3
这个模块是一种简化的BottleneckCSP因为除了Bottleneck部分只有3个卷积可以减少参数所以取名C3。 class C3(nn.Module):# CSP Bottleneck with 3 convolutionsdef __init__(self, c1, c2, n1, shortcutTrue, g1, e0.5): # ch_in, ch_out, number, shortcut, groups, expansion 在C3RT模块和yolo.py的parse_model函数中被调用:params c1: 整个C3的输入channel:params c2: 整个C3的输出channel:params n: 有n个子模块[Bottleneck/CrossConv]:params shortcut: bool值子模块[Bottlenec/CrossConv]中是否有shortcut默认True:params g: 子模块[Bottlenec/CrossConv]中的3x3卷积类型1普通卷积1深度可分离卷积:params e: expansion ratioe*c2中间其它所有层的卷积核个数中间所有层的的输入输出channelsuper().__init__()c_ int(c2 * e) # hidden channelsself.cv1 Conv(c1, c_, 1, 1)self.cv2 Conv(c1, c_, 1, 1)self.cv3 Conv(2 * c_, c2, 1) # optional actFReLU(c2)self.m nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e1.0) for _ in range(n)))# 实验性 CrossConv#self.m nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)])def forward(self, x):return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
1.7 SPP
高层网络层的感受野的语义信息表征能力强低层网络层的感受野空间细节信息表征能力强。空间金字塔池化Spatial Pyramid PoolingSPP是目标检测算法中对高层特征进行多尺度池化以增加感受野的重要措施之一。经典的空间金字塔池化模块首先将输入的卷积特征分成不同的尺寸然后每个尺寸提取固定维度的特征最后将这些特征拼接成一个固定的维度如下图1所示。输入的卷积特征图的大小为(w, h)第一层空间金字塔采用4x4的刻度对特征图进行划分其将输入的特征图分成了16个块每块的大小为(w/4, h/4)第二层空间金字塔采用2x2的刻度对特征图进行划分将特征图分为4个块每块大小为(w/2, h/2)第三层空间金字塔将整张特征图作为一块进行特征提取操作最终的特征向量为164121维。 SPP模块具体的结构如下所示: class SPP(nn.Module):# Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729def __init__(self, c1, c2, k(5, 9, 13)): 在yolo.py的parse_model函数中被调用:params c1: SPP模块的输入channel:params c2: SPP模块的输出channel:params k: 保存着三个maxpool的卷积核大小默认是(5, 9, 13)super().__init__()c_ c1 // 2 # hidden channelsself.cv1 Conv(c1, c_, 1, 1) # 第一层卷积self.cv2 Conv(c_ * (len(k) 1), c2, 1, 1) # 最后一层卷积1是因为有len(k)1个输入self.m nn.ModuleList([nn.MaxPool2d(kernel_sizex, stride1, paddingx // 2) for x in k])def forward(self, x):x self.cv1(x)with warnings.catch_warnings():warnings.simplefilter(ignore) # suppress torch 1.9.0 max_pool2d() warningreturn self.cv2(torch.cat([x] [m(x) for m in self.m], 1))1.8 Concat
这个函数是将自身a list of tensors按照某个维度进行concat通常用来合并前后两个feature map也就是上面yolov5s结构图中的Concat。
class Concat(nn.Module):# Concatenate a list of tensors along dimensiondef __init__(self, dimension1): 在yolo.py的parse_model函数中被调用:params dimension: 沿着哪个维度进行concatsuper().__init__()self.d dimensiondef forward(self, x):# x: a list of tensorsreturn torch.cat(x, self.d)
1.9 Contract、Expand
这两个函数用于改变feature map维度。
Contract函数改变输入特征的shape将feature map的 w 和 h 维度缩小的数据收缩到channel维度上放大。如x(1,64,80,80) to x(1,256,40,40)。 Expand函数也是改变输入特征的shape不过与Contract的相反是将channel维度变小的数据扩展到 W 和 H 维度变大。如x(1,64,80,80) to x(1,16,160,160)。
class Contract(nn.Module):# Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)def __init__(self, gain2): 在yolo.py的parse_model函数中被调用用的不多改变输入特征的shape将w和h维度(缩小)的数据收缩到channel维度上(放大)super().__init__()self.gain gaindef forward(self, x):b, c, h, w x.size() # assert (h / s 0) and (W / s 0), Indivisible gains self.gain # 2x x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2)# permute: 改变tensor的维度顺序x x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)# .view: 改变tensor的维度return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40)class Expand(nn.Module):# Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)def __init__(self, gain2): 在yolo.py的parse_model函数中被调用用的不多改变输入特征的shape将channel维度(变小)的数据扩展到W和H维度上(变大)super().__init__()self.gain gaindef forward(self, x):b, c, h, w x.size() # assert C / s ** 2 0, Indivisible gains self.gain # 2x x.view(b, s, s, c // s ** 2, h, w) # x(1,2,2,16,80,80)x x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)return x.view(b, c // s ** 2, h * s, w * s) # x(1,16,160,160)
2.重要类
下面的几个函数都是属于模型的扩展模块。yolov5的作者将搭建模型的函数功能写的很齐全。不光包含搭建模型部分还考虑到了各方面其它的功能比如给模型搭载NMS功能给模型封装成包含前处理、推理、后处理的模块预处理 推理 NMS二次分类等等功能。
2.1 非极大值抑制NMS
非极大值抑制Non-maximum Suppression(NMS)的作用简单来说就是模型检测出了很多框我们应该留哪些。
YOLOv5中使用NMS算法来移除一些网络模型预测时生成的多余的检测框该算法的核心思想是指搜索局部得分最大值预测并移除与局部最大值预测框重叠度超过一定阈值的检测框需要注意的是NMS算法对所有待检测目标类别分别执行即为不同类别的检测框即使有重叠也不会被移除。 这个模块是给模型搭载NMS功能直接调用的./utils/general.py文件的non_max_suppression()函数。
class NMS(nn.Module): 在yolo.py中Model类的NMS函数中使用NMS非极大值抑制 Non-Maximum Suppression (NMS) module给模型model封装NMS增加模型的扩展功能但我们一般不用一般直接在前向推理结束后再调用non_max_suppression函数conf 0.25 # 置信度阈值iou 0.45 # IOU阈值classes None # 是否NMS后只保留指定的类别max_det 1000 # 每张图的最大目标个数def __init__(self):super(NMS, self).__init__()def forward(self, x)::params x[0]: [batch, num_anchors(3个yolo预测层)(xywh1num_classes)]直接调用的是general.py中的non_max_suppression函数给Model扩展NMS功能return non_max_suppression(x[0], self.conf, iou_thresself.iou, classesself.classes, max_detself.max_det)2.2 AutoShape
这个模块是一个模型扩展模块给模型封装成包含前处理、推理、后处理的模块预处理 推理 NMS用的不多
class AutoShape(nn.Module):# YOLOv5 input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS# YOLOv5模型包装器用于传递 cv2/np/PIL/torch输入# 包括预处理preprocessing、推理inference和NMSconf 0.25 # NMS confidence thresholdiou 0.45 # NMS IoU thresholdagnostic False # NMS class-agnosticmulti_label False # NMS multiple labels per boxclasses None # (optional list) filter by class, i.e. [0, 15, 16] for COCO persons, cats and dogsmax_det 1000 # maximum number of detections per imageamp False # Automatic Mixed Precision (AMP) inferencedef __init__(self, model, verboseTrue):super().__init__()if verbose:LOGGER.info(Adding AutoShape... )copy_attr(self, model, include(yaml, nc, hyp, names, stride, abc), exclude()) # copy attributesself.dmb isinstance(model, DetectMultiBackend) # DetectMultiBackend() instanceself.pt not self.dmb or model.pt # PyTorch model# 开启验证模式self.model model.eval()if self.pt:m self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect()m.inplace False # Detect.inplaceFalse for safe multithread inferencem.export True # do not output loss valuesdef _apply(self, fn):# Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffersself super()._apply(fn)if self.pt:m self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect()m.stride fn(m.stride)m.grid list(map(fn, m.grid))if isinstance(m.anchor_grid, list):m.anchor_grid list(map(fn, m.anchor_grid))return selfsmart_inference_mode()def forward(self, ims, size640, augmentFalse, profileFalse):# Inference from various sources. For size(height640, width1280), RGB images example inputs are:# file: ims data/images/zidane.jpg # str or PosixPath# URI: https://ultralytics.com/images/zidane.jpg# OpenCV: cv2.imread(image.jpg)[:,:,::-1] # HWC BGR to RGB x(640,1280,3)# PIL: Image.open(image.jpg) or ImageGrab.grab() # HWC x(640,1280,3)# numpy: np.zeros((640,1280,3)) # HWC# torch: torch.zeros(16,3,320,640) # BCHW (scaled to size640, 0-1 values)# multiple: [Image.open(image1.jpg), Image.open(image2.jpg), ...] # list of imagesdt (Profile(), Profile(), Profile())with dt[0]:if isinstance(size, int): # expandsize (size, size)p next(self.model.parameters()) if self.pt else torch.empty(1, deviceself.model.device) # paramautocast self.amp and (p.device.type ! cpu) # Automatic Mixed Precision (AMP) inference# 图片如果是tensor格式说明是预处理过的直接正常进行前向推理即可NMS在推理结束进行(函数外写)if isinstance(ims, torch.Tensor): # torchwith amp.autocast(autocast):return self.model(ims.to(p.device).type_as(p), augmentaugment) # inference# Pre-processn, ims (len(ims), list(ims)) if isinstance(ims, (list, tuple)) else (1, [ims]) # number, list of imagesshape0, shape1, files [], [], [] # image and inference shapes, filenamesfor i, im in enumerate(ims):f fimage{i} # filenameif isinstance(im, (str, Path)): # filename or uriim, f Image.open(requests.get(im, streamTrue).raw if str(im).startswith(http) else im), imim np.asarray(exif_transpose(im))elif isinstance(im, Image.Image): # PIL Imageim, f np.asarray(exif_transpose(im)), getattr(im, filename, f) or ffiles.append(Path(f).with_suffix(.jpg).name)if im.shape[0] 5: # image in CHWim im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)im im[..., :3] if im.ndim 3 else cv2.cvtColor(im, cv2.COLOR_GRAY2BGR) # enforce 3ch inputs im.shape[:2] # HWCshape0.append(s) # image shapeg max(size) / max(s) # gainshape1.append([int(y * g) for y in s])ims[i] im if im.data.contiguous else np.ascontiguousarray(im) # updateshape1 [make_divisible(x, self.stride) for x in np.array(shape1).max(0)] # inf shapex [letterbox(im, shape1, autoFalse)[0] for im in ims] # padx np.ascontiguousarray(np.array(x).transpose((0, 3, 1, 2))) # stack and BHWC to BCHWx torch.from_numpy(x).to(p.device).type_as(p) / 255 # uint8 to fp16/32with amp.autocast(autocast):# Inferencewith dt[1]:y self.model(x, augmentaugment) # forward# Post-processwith dt[2]:y non_max_suppression(y if self.dmb else y[0],self.conf,self.iou,self.classes,self.agnostic,self.multi_label,max_detself.max_det) # NMSfor i in range(n):scale_boxes(shape1, y[i][:, :4], shape0[i])return Detections(ims, y, files, dt, self.names, x.shape)2.3 Detections
这是专门针对目标检测的封装类。
class Detections:# YOLOv5 detections class for inference results# YOLOv5推理结果检测类def __init__(self, ims, pred, files, times(0, 0, 0), namesNone, shapeNone):super().__init__()d pred[0].device # devicegn [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], deviced) for im in ims] # normalizationsself.ims ims # list of images as numpy arraysself.pred pred # list of tensors pred[0] (xyxy, conf, cls)self.names names # class namesself.files files # image filenamesself.times times # profiling timesself.xyxy pred # xyxy pixelsself.xywh [xyxy2xywh(x) for x in pred] # xywh pixelsself.xyxyn [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalizedself.xywhn [x / g for x, g in zip(self.xywh, gn)] # xywh normalizedself.n len(self.pred) # number of images (batch size)self.t tuple(x.t / self.n * 1E3 for x in times) # timestamps (ms)self.s tuple(shape) # inference BCHW shapedef _run(self, pprintFalse, showFalse, saveFalse, cropFalse, renderFalse, labelsTrue, save_dirPath()):s, crops , []for i, (im, pred) in enumerate(zip(self.ims, self.pred)):s f\nimage {i 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} # stringif pred.shape[0]:for c in pred[:, -1].unique():n (pred[:, -1] c).sum() # detections per classs f{n} {self.names[int(c)]}{s * (n 1)}, # add to strings s.rstrip(, )if show or save or render or crop:annotator Annotator(im, examplestr(self.names))for *box, conf, cls in reversed(pred): # xyxy, confidence, classlabel f{self.names[int(cls)]} {conf:.2f}if crop:file save_dir / crops / self.names[int(cls)] / self.files[i] if save else Nonecrops.append({box: box,conf: conf,cls: cls,label: label,im: save_one_box(box, im, filefile, savesave)})else: # all othersannotator.box_label(box, label if labels else , colorcolors(cls))im annotator.imelse:s (no detections)im Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from npif show:display(im) if is_notebook() else im.show(self.files[i])if save:f self.files[i]im.save(save_dir / f) # saveif i self.n - 1:LOGGER.info(fSaved {self.n} image{s * (self.n 1)} to {colorstr(bold, save_dir)})if render:self.ims[i] np.asarray(im)if pprint:s s.lstrip(\n)return f{s}\nSpeed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {self.s} % self.tif crop:if save:LOGGER.info(fSaved results to {save_dir}\n)return cropsTryExcept(Showing images is not supported in this environment)def show(self, labelsTrue):self._run(showTrue, labelslabels) # show resultsdef save(self, labelsTrue, save_dirruns/detect/exp, exist_okFalse):save_dir increment_path(save_dir, exist_ok, mkdirTrue) # increment save_dirself._run(saveTrue, labelslabels, save_dirsave_dir) # save resultsdef crop(self, saveTrue, save_dirruns/detect/exp, exist_okFalse):save_dir increment_path(save_dir, exist_ok, mkdirTrue) if save else Nonereturn self._run(cropTrue, savesave, save_dirsave_dir) # crop resultsdef render(self, labelsTrue):self._run(renderTrue, labelslabels) # render resultsreturn self.imsdef pandas(self):# return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])new copy(self) # return copyca xmin, ymin, xmax, ymax, confidence, class, name # xyxy columnscb xcenter, ycenter, width, height, confidence, class, name # xywh columnsfor k, c in zip([xyxy, xyxyn, xywh, xywhn], [ca, ca, cb, cb]):a [[x[:5] [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # updatesetattr(new, k, [pd.DataFrame(x, columnsc) for x in a])return newdef tolist(self):# return a list of Detections objects, i.e. for result in results.tolist():r range(self.n) # iterablex [Detections([self.ims[i]], [self.pred[i]], [self.files[i]], self.times, self.names, self.s) for i in r]# for d in x:# for k in [ims, pred, xyxy, xyxyn, xywh, xywhn]:# setattr(d, k, getattr(d, k)[0]) # pop out of listreturn xdef print(self):LOGGER.info(self.__str__())def __len__(self): # override len(results)return self.ndef __str__(self): # override print(results)return self._run(pprintTrue) # print resultsdef __repr__(self):return fYOLOv5 {self.__class__} instance\n self.__str__()2.4 Classify
这是一个二级分类模块。什么是二级分类模块比如做车牌识别先识别出车牌如果相对车牌上的字进行识别就需要二级分类进一步检测。
class Classify(nn.Module):# YOLOv5 classification head, i.e. x(b,c1,20,20) to x(b,c2)def __init__(self, c1, c2, k1, s1, pNone, g1): # ch_in, ch_out, kernel, stride, padding, groups 这是一个二级分类模块如果对模型输出的分类在进行分类就可以用这个模块。不过这里这个类写的比较简单若进行复杂的二级分类可以根据自己的实际任务改下这里代码不唯一。super().__init__()c_ 1280 # efficientnet_b0 sizeself.conv Conv(c1, c_, k, s, autopad(k, p), g)self.pool nn.AdaptiveAvgPool2d(1) # to x(b,c_,1,1)self.drop nn.Dropout(p0.0, inplaceTrue)self.linear nn.Linear(c_, c2) # to x(b,c2)def forward(self, x):if isinstance(x, list):x torch.cat(x, 1)return self.linear(self.drop(self.pool(self.conv(x)).flatten(1)))C3模块修改如下去掉concat后的卷积层
class C3(nn.Module):# CSP Bottleneck with 3 convolutionsdef __init__(self, c1, c2, n1, shortcutTrue, g1, e0.5): # ch_in, ch_out, number, shortcut, groups, expansion 在C3RT模块和yolo.py的parse_model函数中被调用:params c1: 整个C3的输入channel:params c2: 整个C3的输出channel:params n: 有n个子模块[Bottleneck/CrossConv]:params shortcut: bool值子模块[Bottlenec/CrossConv]中是否有shortcut默认True:params g: 子模块[Bottlenec/CrossConv]中的3x3卷积类型1普通卷积1深度可分离卷积:params e: expansion ratioe*c2中间其它所有层的卷积核个数中间所有层的的输入输出channelsuper().__init__()c_ int(c2 * e) # hidden channelsself.cv1 Conv(c1, c_, 1, 1)self.cv2 Conv(c1, c_, 1, 1)self.cv3 Conv(2 * c_, c2, 1) # optional actFReLU(c2)self.m nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e1.0) for _ in range(n)))# 实验性 CrossConv#self.m nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)])def forward(self, x):#return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))# 移除cv3卷积层后若要保持最终输出的channel仍为c2则中间层的channel需为c2/2# 设置e0.5即可取默认值不变return torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1)