YOLOv5-Y4周:common.py文件解读

 本文为🔗365天深度学习训练营 中的学习记录博客
 原作者:K同学啊|接辅导、项目定制

我的环境:

1.语言:python3.7

2.编译器:pycharm


common.py存放了YOLO算法的各个模块,接下来我们将了解每个模块的定义。

1.1、autopad

def autopad(k, p=None, d=1):  # kernel, padding, dilation
    # Pad to 'same' shape outputs
    if d > 1:
        k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k]  # actual kernel-size
    if p is None:
        p = k // 2 if isinstance(k, int) else [x // 2 for x in k]  # auto-pad
    return p

用于Conv与Classify函数中。根据卷积核大小自动计算卷积核的填充数。

k:卷积核的大小

p:自动计算的填充值

1.2、Conv

由卷积层+BN层+激活函数组成

class Conv(nn.Module):
    # Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)
    default_act = nn.SiLU()  # default activation

    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
        super().__init__()
        self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
        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):
        return self.act(self.conv(x))

c1:输入的通道值

c2:输出的通道值

k :卷积的kernel_size

s:卷积的步长

p:卷积的padding一般是None可以通过autopad自行计算需要pad的padding数

g:卷积的groups数―=1就是普通的卷积>1就是深度可分离卷积

act:激活函数类型True就是siLu()/Swish False就是不使用激活函数 类型是nn. Module就使用传进来的激活函数类型

fuseforward函数是前向加速推理模块,在前向传播的过程中,通过融合conv+bn层,达到加速推理的作用。

1.3、Focus

class Focus(nn.Module):
    # Focus wh information into c-space
    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):  # ch_in, ch_out, kernel, stride, padding, groups
        super().__init__()
        self.conv = Conv(c1 * 4, c2, k, s, p, g, act=act)
        # self.contract = Contract(gain=2)

    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))

Focus模块是作者自己设计出来,为了减少浮点数和提高速度,本质是将图像进行切片,将原图像的宽高信息切分,聚合到channel通道中。

forward 方法定义了前向传播过程。

输入 x 是一个四维张量,表示为 (batch_size, channels, width, height)。
通过 torch.cat 将输入张量按照通道维度进行拼接。具体来说,将输入的特征图沿着通道维度分成4个部分,然后将这4个部分在通道维度上拼接在一起。
最终,将拼接后的张量传递给之前定义的 self.conv,即使用普通卷积进行处理。


1.4、Bottleneck

class Bottleneck(nn.Module):
    # Standard bottleneck
    def __init__(self, c1, c2, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, shortcut, groups, expansion
        super().__init__()
        c_ = int(c2 * e)  # hidden channels
        # 1*1卷积层
        self.cv1 = Conv(c1, c_, 1, 1)
        # 3*3卷积层
        self.cv2 = Conv(c_, c2, 3, 1, g=g)
        # shortcut=True 并且 c1==c2 才能做shortcut, 将输入和输出相加之后再输出
        self.add = shortcut and c1 == c2

    def forward(self, x):
        return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))

c1:第一个卷积的输入channel
c2:第二个卷积的输出channel
shortcut:bool 是否有shortcut连接,默认为True
g:表示从输入通道到输出通道的阻塞连接数。卷积分组的个数: =1就是普通卷积 >1就是深度可分离卷积
e:expansion ratio e*c2 就是第一个卷积的输出channel=第二个卷积的输入channel

1.4、BottleneckCSP

class BottleneckCSP(nn.Module):
    # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
    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 = nn.Conv2d(c1, c_, 1, 1, bias=False)
        self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
        self.cv4 = Conv(2 * c_, c2, 1, 1)
        self.bn = nn.BatchNorm2d(2 * c_)  # applied to cat(cv2, cv3)
        self.act = nn.SiLU()
        self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.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))))

c1:整个BottleneckCSP的输入channel
c2:整个BottleneckCSP的输出channel
n:有n个Bottleneck
shortcut:bool Bottleneck中是否有shortcut连接,默认为True
g:表示从输入通道到输出通道的阻塞连接数。Bottleneck中的3x3卷积类型: =1就是普通卷积 >1就是深度可分离卷积
e:expansion ratio c2xe=中间其他所有层的卷积核个数/中间所有层的输入输出channel数
torch.cat((y1,y2), dim=1):这里是指定第11个维度上进行合并,即再channel维度上合并
c_:bottleneckCSP结构的中间层的通道数,由膨胀率e决定
 

1.6、C3

这是一种简化般的BottleneckCSP,因为除了Bottleneck部分只有三个卷积,可以减少参数

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
        
        # 3个1*1卷积层的堆叠,比BottleneckCSP少一个
        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))

c1:整个BottleneckCSP的输入channel
c2:整个BottleneckCSP的输出channel
n:有n个Bottleneck
shortcut:bool Bottleneck中是否有shortcut连接,默认为True
g:表示从输入通道到输出通道的阻塞连接数。Bottleneck中的3x3卷积类型: =1就是普通卷积 >1就是深度可分离卷积
e:expansion ratio c2xe=中间其他所有层的卷积核个数/中间所有层的输入输出channel数
torch.cat((y1,y2), dim=1):这里是指定第11个维度上进行合并,即再channel维度上合并
c_:bottleneckCSP结构的中间层的通道数,由膨胀率e决定
 

1.7、SPP

class SPP(nn.Module):
    # Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729
    def __init__(self, c1, c2, k=(5, 9, 13)):
        super().__init__()
        c_ = c1 // 2  # hidden channels
        self.cv1 = Conv(c1, c_, 1, 1)
        self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
        self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 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() warning
            return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))

SPP(Spatial Pyramid Pooling)空间金字塔池化模块,用在骨干网络收尾阶段,用于融合多尺度特征。这个模块的主要作用是为了将更过不同分辨率的特征进行融合,得到更多的信息。

高层网络层的感受野的语义信息表征能力强,低层网络层的感受野空间细节信息表征能力强。

SPP是目标检测算法中对高层特征进行多尺度池化以增加感受野的重要措施之一。

**经典的空间金字塔池化模块:**1、将输入的卷积特征分成不同尺寸 ----> 2、每个尺寸提取固定维度的特征 ----> 3、将这些特征拼接成一个固定的维度。

**如图所示:**输入的卷积特征图的大小为(w,h),

​ **第一层空间金字塔:**采用 4*4 的刻度对特征图进行划分,其将输入的特征图分成 16 个块,每块大小为 (w/4, h/4) ;

​ **第二层空间金字塔:**采用 2*2 的刻度对特征图进行划分,其将输入的特征图分成 4 个块,每块大小为 (w/2, h/2) ;

​ **第三层空间金字塔:**将整张特征图作为一块,今昔特征提取操作,最终的特征向量为 21=16+4+1 维。
 

1.8、Contract

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, gain=2):
        super().__init__()
        self.gain = gain

    def forward(self, x):
        b, c, h, w = x.size()  # assert (h / s == 0) and (W / s == 0), 'Indivisible gain'
        s = self.gain
        x = 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)

 

Contract是收缩模块。调整张量的大小,将宽高收缩到通道中。

Contract 函数改变输入特征的shape,将feature map的 w 和 h 维度(缩小)的数据收缩到channel维度上(放大)。

如:当gain = 2时,x(1,64,80,80)的图像 ----> x(1,256,40,40)的图像。其操作类Focus,但更灵活,并且少一个卷积。
 

1.9、Concat

class Concat(nn.Module):
    # Concatenate a list of tensors along dimension
    def __init__(self, dimension=1):
        super().__init__()
        self.d = dimension

    def forward(self, x):
        return torch.cat(x, self.d)

Concat是拼接函数,将两个tensor拼接起来。在yolo.py的parse_model模块调用。

这个是自定义模块,dimension是维度值,说明沿着哪一个维度进行拼接。当dimension=1时,将多张相同尺寸的图像在通道维度上拼接(通道数可能不同)。

这个函数是讲自身(a list of tensors)按照某个维度进行concat,常用来合并前后两个feature map, 也就是yolov5结构图中的Concat。
 

2.1、非极大值抑制(NMS)

class NMS(nn.Module):
    """在yolo.py中Model类的nms函数中使用
    NMS非极大值抑制 Non-Maximum Suppression (NMS) module
    给模型model封装nms  增加模型的扩展功能  但是我们一般不用 一般是在前向推理结束后再调用non_max_suppression函数
    """
    conf = 0.25     # 置信度阈值              confidence threshold
    iou = 0.45      # iou阈值                IoU threshold
    classes = None  # 是否nms后只保留特定的类别 (optional list) filter by class
    max_det = 1000  # 每张图片的最大目标个数    maximum number of detections per image
    def __init__(self):
        super(NMS, self).__init__()
    def forward(self, x):
        """
        :params x[0]: [batch, num_anchors(3个yolo预测层), (x+y+w+h+1+num_classes)]
        直接调用的是general.py中的non_max_suppression函数给model扩展nms功能
        """
        return non_max_suppression(x[0], self.conf, iou_thres=self.iou, classes=self.classes, max_det=self.max_det)
 

  num_anchors, (x+y+w+h+1+num_classes)]。该方法直接调用了 non_max_suppression 函数,该函数应该定义在 general.py 中。non_max_suppression 函数的作用是对模型的输出进行非极大值抑制,过滤掉置信度低、重叠度高的目标框。
  NMS 模块的目的是通过非极大值抑制过程对模型的输出进行后处理,保留具有高置信度的目标框,过滤掉置信度低或者与其他框重叠度高的目标框。这个模块通常在模型推理结束后用于后处理步骤。

2.2、AutoShape

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) and NMS
    conf = 0.25  # NMS confidence threshold
    iou = 0.45   # NMS IoU threshold
    agnostic = False  # NMS class-agnostic
    multi_label = False  # NMS multiple labels per box
    classes = None  # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs
    max_det = 1000  # maximum number of detections per image
    amp = False     # Automatic Mixed Precision (AMP) inference
 
    def __init__(self, model, verbose=True):
        super().__init__()
        if verbose:
            LOGGER.info('Adding AutoShape... ')
        copy_attr(self, model, include=('yaml', 'nc', 'hyp', 'names', 'stride', 'abc'), exclude=())  # copy attributes
        self.dmb = isinstance(model, DetectMultiBackend)  # DetectMultiBackend() instance
        self.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.inplace=False for safe multithread inference
            m.export = True  # do not output loss values
 
    def _apply(self, fn):
        # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
        self = 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 self
 
    @smart_inference_mode()
    def forward(self, ims, size=640, augment=False, profile=False):
        # Inference from various sources. For size(height=640, width=1280), 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 size=640, 0-1 values)
        #   multiple:        = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...]  # list of images
 
        dt = (Profile(), Profile(), Profile())
        with dt[0]:
            if isinstance(size, int):  # expand
                size = (size, size)
            p = next(self.model.parameters()) if self.pt else torch.empty(1, device=self.model.device)  # param
            autocast = self.amp and (p.device.type != 'cpu')  # Automatic Mixed Precision (AMP) inference
            # 图片如果是tensor格式 说明是预处理过的, 
            # 直接正常进行前向推理即可 nms在推理结束进行(函数外写)
            if isinstance(ims, torch.Tensor):  # torch
                with amp.autocast(autocast):
                    return self.model(ims.to(p.device).type_as(p), augment=augment)  # inference
 
            # Pre-process
            n, ims = (len(ims), list(ims)) if isinstance(ims, (list, tuple)) else (1, [ims])  # number, list of images
            shape0, shape1, files = [], [], []  # image and inference shapes, filenames
            for i, im in enumerate(ims):
                f = f'image{i}'  # filename
                if isinstance(im, (str, Path)):  # filename or uri
                    im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im
                    im = np.asarray(exif_transpose(im))
                elif isinstance(im, Image.Image):  # PIL Image
                    im, f = np.asarray(exif_transpose(im)), getattr(im, 'filename', f) or f
                files.append(Path(f).with_suffix('.jpg').name)
                if im.shape[0] < 5:  # image in CHW
                    im = 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 input
                s = im.shape[:2]  # HWC
                shape0.append(s)  # image shape
                g = max(size) / max(s)  # gain
                shape1.append([int(y * g) for y in s])
                ims[i] = im if im.data.contiguous else np.ascontiguousarray(im)  # update
            shape1 = [make_divisible(x, self.stride) for x in np.array(shape1).max(0)]  # inf shape
            x = [letterbox(im, shape1, auto=False)[0] for im in ims]  # pad
            x = np.ascontiguousarray(np.array(x).transpose((0, 3, 1, 2)))  # stack and BHWC to BCHW
            x = torch.from_numpy(x).to(p.device).type_as(p) / 255  # uint8 to fp16/32
 
        with amp.autocast(autocast):
            # Inference
            with dt[1]:
                y = self.model(x, augment=augment)  # forward
            # Post-process
            with 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_det=self.max_det)  # NMS
                for i in range(n):
                    scale_boxes(shape1, y[i][:, :4], shape0[i])
            return Detections(ims, y, files, dt, self.names, x.shape)
 

 AutoShape的PyTorch模块(nn.Module)类,用于对YOLOv5模型进行封装,以实现对不同输入类型的适应性(cv2/np/PIL/torch)。

__init__ 方法是类的初始化方法,用于初始化参数。

model: YOLOv5模型实例。
verbose: 是否在初始化时输出日志信息。
_apply 方法用于将函数应用于模型张量,支持对模型张量的操作。

forward 方法定义了前向传播过程。

ims: 输入的图像数据,可以是单张图像的路径、URL、OpenCV读取的图像(HWC BGR格式),PIL读取的图像(HWC格式),numpy数组(HWC格式),torch张量(BCHW格式),或图像列表。
size: 期望输入图像的大小,可以是单个整数表示高和宽相等,也可以是包含高和宽的元组。
augment: 是否进行数据增强。
profile: 是否开启推理性能分析。
 

2.3、Detections

 
class Detections:
    # YOLOv5 detections class for inference results
    # YOLOv5推理结果检测类
    def __init__(self, ims, pred, files, times=(0, 0, 0), names=None, shape=None):
        super().__init__()
        d = pred[0].device  # device
        gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], device=d) for im in ims]  # normalizations
        self.ims = ims  # list of images as numpy arrays
        self.pred = pred  # list of tensors pred[0] = (xyxy, conf, cls)
        self.names = names  # class names
        self.files = files  # image filenames
        self.times = times  # profiling times
        self.xyxy = pred  # xyxy pixels
        self.xywh = [xyxy2xywh(x) for x in pred]  # xywh pixels
        self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)]  # xyxy normalized
        self.xywhn = [x / g for x, g in zip(self.xywh, gn)]  # xywh normalized
        self.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 shape
 
    def _run(self, pprint=False, show=False, save=False, crop=False, render=False, labels=True, save_dir=Path('')):
        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]} '  # string
            if pred.shape[0]:
                for c in pred[:, -1].unique():
                    n = (pred[:, -1] == c).sum()  # detections per class
                    s += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, "  # add to string
                s = s.rstrip(', ')
                if show or save or render or crop:
                    annotator = Annotator(im, example=str(self.names))
                    for *box, conf, cls in reversed(pred):  # xyxy, confidence, class
                        label = f'{self.names[int(cls)]} {conf:.2f}'
                        if crop:
                            file = save_dir / 'crops' / self.names[int(cls)] / self.files[i] if save else None
                            crops.append({
                                'box': box,
                                'conf': conf,
                                'cls': cls,
                                'label': label,
                                'im': save_one_box(box, im, file=file, save=save)})
                        else:  # all others
                            annotator.box_label(box, label if labels else '', color=colors(cls))
                    im = annotator.im
            else:
                s += '(no detections)'
 
            im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im  # from np
            if show:
                display(im) if is_notebook() else im.show(self.files[i])
            if save:
                f = self.files[i]
                im.save(save_dir / f)  # save
                if i == self.n - 1:
                    LOGGER.info(f"Saved {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.t
        if crop:
            if save:
                LOGGER.info(f'Saved results to {save_dir}\n')
            return crops
 
    @TryExcept('Showing images is not supported in this environment')
    def show(self, labels=True):
        self._run(show=True, labels=labels)  # show results
 
    def save(self, labels=True, save_dir='runs/detect/exp', exist_ok=False):
        save_dir = increment_path(save_dir, exist_ok, mkdir=True)  # increment save_dir
        self._run(save=True, labels=labels, save_dir=save_dir)  # save results
 
    def crop(self, save=True, save_dir='runs/detect/exp', exist_ok=False):
        save_dir = increment_path(save_dir, exist_ok, mkdir=True) if save else None
        return self._run(crop=True, save=save, save_dir=save_dir)  # crop results
 
    def render(self, labels=True):
        self._run(render=True, labels=labels)  # render results
        return self.ims
 
    def pandas(self):
        # return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])
        new = copy(self)  # return copy
        ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name'  # xyxy columns
        cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name'  # xywh columns
        for 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)]  # update
            setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
        return new
 
    def tolist(self):
        # return a list of Detections objects, i.e. 'for result in results.tolist():'
        r = range(self.n)  # iterable
        x = [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 list
        return x
 
    def print(self):
        LOGGER.info(self.__str__())
 
    def __len__(self):  # override len(results)
        return self.n
 
    def __str__(self):  # override print(results)
        return self._run(pprint=True)  # print results
 
    def __repr__(self):
        return f'YOLOv5 {self.__class__} instance\n' + self.__str__()
 

Detections的类,用于存储YOLOv5的推理结果。

ims: 输入图像列表,每个元素是一个图像的 numpy 数组。
pred: 模型的推理结果列表,每个元素是一个 tensor,表示该图像的预测框信息。
files: 图像文件名列表。
times: 推理时间的元组,包含预处理、推理和NMS的时间。
names: 类别名称列表。
shape: 推理时输入的图像尺寸。
_run 方法用于展示、保存、裁剪、渲染图像等操作。

pprint: 是否输出详细信息。
show: 是否显示图像。
save: 是否保存图像。
crop: 是否裁剪图像。
render: 是否渲染图像。
labels: 是否显示标签。
save_dir: 保存图像的目录。
show, save, crop, render 方法分别用于显示、保存、裁剪、渲染图像。

pandas 方法将检测结果转换为 Pandas 的 DataFrame 格式。

tolist 方法返回一个由 Detections 对象组成的列表。

print 方法用于打印 Detections 对象的详细信息。

__len__, __str__, __repr__ 方法用于获取 Detections 对象的长度、字符串表示和打印形式。
 

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,
                 k=1,
                 s=1,
                 p=None,
                 g=1,
                 dropout_p=0.0):  # ch_in, ch_out, kernel, stride, padding, groups, dropout probability
        super().__init__()
        c_ = 1280  # efficientnet_b0 size
        self.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(p=dropout_p, inplace=True)
        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)))

二级分类模块,当我们对车牌进行检测时,先识别出车牌,若想对车牌上的字进行识别就需要二级分类进一步检测。

3.1、C3修改

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.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))

    def forward(self, x):
        return torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1)

运行结果:

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值