365天深度学习打卡 YOLOv5白皮书-第Y4周:common.py文件解读

news2024/9/29 23:26:42

YOLOv5白皮书-第Y4周:common.py文件解读

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

文件位置:./models/common.py
该文件是实现YOLO算法中各个模块的地方,如果我们需要修改某一模块(例如C3),那么就需要修改这个文件中对应模块的的定义。这里我先围绕代码,带大家过一遍各个模块的 定义,详细介绍我将在后续的教案中逐步展开。由于YOLOV5版本问题,同一个模块你可能会看到不同的版本,这都是正常的,以官网为主即可。
本周任务:将yolov5s网络模型中的C3模块按照下图方式修改,并跑通yolov5。
任务提示:仅需修改・/models/common.yaml文件。

在这里插入图片描述
在这里插入图片描述

完成任务:

import torch
import torch.nn as nn
class Bottleneck(nn.Module):
    # Standard bottleneck  Conv + Conv + shortcut
    def __init__(self, c1, c2, shortcut=True, g=1, e=0.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 ratio,e*c2就是第一个卷积的输出channel=第二个卷积的输入channel
        '''
        super().__init__()
        c_ = int(c2 * e)  # hidden channels
        self.cv1 = Conv(c1, c_, 1, 1)      # 1x1
        self.cv2 = Conv(c_, c2, 3, 1, g=g) # 3x3
        self.add = shortcut and c1 == c2   # shortcut=Ture & c1==c2 才能做shortcut

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

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

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):
        ''' 在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()/Swish,False就是不使用激活函数,类型是nn.Module就使用传进来的激活函数类型
        '''
        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):
        ''' 用于Model类的fuse函数
        融合 Conv + BN 加速推理,一般用于测试/验证阶段
        '''
        return self.act(self.conv(x))
''''''
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
        ''' 在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 ratio,e*c2=中间其它所有层的卷积核个数=中间所有层的的输入输出channel
        '''
        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)))
        # 实验性 CrossConv
        #self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)])

    def forward(self, x):
        return self.torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1)
''''''
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 torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1)
x = torch.randn(1,32,120,120)
c3 = C3(32,64)
output = c3(x)
print(output.shape)

经测试:
在这里插入图片描述

def autopad(k, p=None):   # kernel, padding
	"""
	用于Conv函数和Classify函数中
    根据卷积核大小k自动计算卷积核padding数(0填充) 
    v5中只有两种卷积:
       1、下采样卷积:conv3x3 s=2 p=k//2=1 
       2、feature size不变的卷积:conv1x1 s=1 p=k//2=1
    :params k: 卷积核的kernel_size
    :return p: 自动计算的需要pad值(0填充)
    """
	if p is None:
        p = k // 2 if isinstance(k,int) else [x // 2 for x in k]  # auto-pad
    return p

另外这个类中还有一个特殊函数 forward_fuse ,这是一个前向加速推理模块,在前向传播过程中,通过融合 Conv + BN 层,达到加速推理的作用,一般用于测试或验证阶段。


class Conv(nn.Module):
    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):
        """
        在Focus、Bottleneck、BottleneckCSP、C3、SPP、DWConv、TransformerBloc等模块中调用
        Standard convolution  conv+BN+act
        :params c1: 输入的channel值
        :params c2: 输出的channel值
        :params k: 卷积的kernel_size
        :params s: 卷积的stride
        :params p: 卷积的padding  一般是None  可以通过autopad自行计算需要pad的padding数
        :params g: 卷积的groups数  =1就是普通的卷积  >1就是深度可分离卷积
        :params act: 激活函数类型   True就是SiLU()/Swish   False就是不使用激活函数
                     类型是nn.Module就使用传进来的激活函数类型
        """
        super(Conv, self).__init__()
        self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)  # conv
        self.bn = nn.BatchNorm2d(c2)  # bn
        self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())  # activation

    def forward(self, x):
        return self.act(self.bn(self.conv(x)))

    def fuseforward(self, x):
        """
        用于Model类的fuse函数
        融合conv+bn 加速推理 一般用于测试/验证阶段
        """
        return self.act(self.conv(x))

在这里插入图片描述

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

class Focus(nn.Module):
    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):
        super(Focus, self).__init__()
        self.conv = Conv(c1 * 4, c2, k, s, p, g, act)  # concat后的卷积(最后的卷积)
    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))

class Bottleneck(nn.Module):
    def __init__(self, c1, c2, shortcut=True, g=1, e=0.5):
        """在BottleneckCSP和yolo.py的parse_model中调用
        Standard bottleneck  Conv+Conv+shortcut
        :params c1: 第一个卷积的输入channel
        :params c2: 第二个卷积的输出channel
        :params shortcut: bool 是否有shortcut连接 默认是True
        :params g: 卷积分组的个数  =1就是普通卷积  >1就是深度可分离卷积
        :params e: expansion ratio  e*c2就是第一个卷积的输出channel=第二个卷积的输入channel
        """
        super(Bottleneck, self).__init__()
        c_ = int(c2 * e)                    # hidden channels
        self.cv1 = Conv(c1, c_, 1, 1)       # 1x1
        self.cv2 = Conv(c_, c2, 3, 1, g=g)  # 3x3
        self.add = shortcut and c1 == c2    # shortcut=True and c1 == c2 才能做shortcut

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

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):
    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
        """在C3模块和yolo.py的parse_model模块调用
        CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
        :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 ratio c2xe=中间其他所有层的卷积核个数/中间所有层的输入输出channel数
        """
        # ch_in, ch_out, number, shortcut, groups, expansion
        super(BottleneckCSP, self).__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)  2*c_
        self.act = nn.LeakyReLU(0.1, inplace=True)
        # 叠加n次Bottleneck
        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), dim=1))))

SPP模块
高层网络层的感受野的语义信息表征能力强,低层网络层的感受野空间细节信息表征能力强。空间金字塔池化(Spatial Pyramid Pooling, SPP)是目标检测算法中对高层特征进行多尺度池化以增加感受野的重要措施之一。经典的空间金字塔池化模块首先将输入的卷积特征分成不同的尺寸,然后每个尺寸提取固定维度的特征,最后将这些特征拼接成一个固定的维度,如图1所示。输入的卷积特征图的大小为(w,h),第一层空间金字塔采用4x4的刻度对特征图进行划分,其将输入的特征图分成了16个块,每块的大小为(w/4, h/4);第二层空间金字塔采用2x2刻度对特征图进行划分,其将特征图分为4个快,每块大小为(w/2,h/2);第三层空间金字塔将整张特征图作为一块,进行特征提取操作,最终的特 征向量为21=16+4+1维。

在这里插入图片描述
在这里插入图片描述

class SPP(nn.Module):
    def __init__(self, c1, c2, k=(5, 9, 13)):
        """在yolo.py的parse_model模块调用
        空间金字塔池化 Spatial pyramid pooling layer used in YOLOv3-SPP
        :params c1: SPP模块的输入channel
        :params c2: SPP模块的输出channel
        :params k: 保存着三个maxpool的卷积核大小 默认是(5, 9, 13)
        """
        super(SPP, self).__init__()
        c_ = c1 // 2  # hidden channels
        self.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_size=x, stride=1, padding=x // 2) for x in k])

    def forward(self, x):
        x = self.cv1(x)
        return self.cv2(torch.cat([x] + [m(x) for m in self.m], 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     # 置信度阈值              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)

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


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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/438180.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Cpp】手撕搜索二叉树(KV模型)

文章目录 二叉搜索树的应用搜索二叉树(KV模型)代码:二叉搜索树的性能分析 二叉搜索树的应用 K模型&#xff1a;K模型即只有key作为关键码&#xff0c;结构中只需要存储Key即可&#xff0c;关键码即为需要搜索到的值。 比如&#xff1a;给一个单词word&#xff0c;判断该单词是…

水果FL Studio21最新中文完整版下载更新及内容介绍

简单总结一下&#xff0c;本次小版本更新最重要的内容&#xff0c;我个人认为是对于M1芯片的适配。其余的比如EQ2&#xff0c;3x这些我们很熟悉的插件虽说也有更新&#xff0c;但是估计并没有特别大的改动。我个人的话会先放一段时间&#xff0c;等下次有其他更让我感兴趣的内容…

吃透SpringMVC面试八股文

说说你对 SpringMVC 的理解 SpringMVC是一种基于 Java 的实现MVC设计模型的请求驱动类型的轻量级Web框架&#xff0c;属于Spring框架的一个模块。 它通过一套注解&#xff0c;让一个简单的Java类成为处理请求的控制器&#xff0c;而无须实现任何接口。同时它还支持RESTful编程…

【智能电网】智能电网中针对DOS和FDIA的弹性分布式EMA(Matlab代码实现)

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 ⛳️座右铭&a…

burpsuite的基本使用

一&#xff0c;Proxy&#xff08;代理&#xff09; 目录 一&#xff0c;Proxy&#xff08;代理&#xff09; 1.1 intercept &#xff08;拦截&#xff09; 1.2 HTTP history&#xff08;HTTP历史记录&#xff09; 1.3 WebSockets history 1.4 options&#xff08;选项&am…

转换CAJ到PDF: 教你如何转换这两种文件格式

在现代信息化社会中&#xff0c;我们常常需要处理各种文件格式&#xff0c;例如常见的文本文档、PDF、图片、视频等等。其中&#xff0c;学术界或者专业人士常常会接触到一种叫做CAJ格式的文件&#xff0c;而这个格式在阅读、编辑以及分享方面可能存在一些限制。为了解决这个问…

影响LED显示屏使用的因素

LED显示屏和其他物品一样&#xff0c;在使用中不免遇到这样或那样的问题。在使用LED显示屏的时候&#xff0c;可能会因散热设计、混灯八个问题&#xff0c;导致困难或影响LED显示屏的使用。而为能使LED显示屏的后期使用效能稳定&#xff0c;首先要做的就是预防它的老化。下面为…

Python OpenCV3 计算机视觉秘籍:6~9

原文&#xff1a;OpenCV 3 Computer Vision with Python Cookbook 协议&#xff1a;CC BY-NC-SA 4.0 译者&#xff1a;飞龙 本文来自【ApacheCN 计算机视觉 译文集】&#xff0c;采用译后编辑&#xff08;MTPE&#xff09;流程来尽可能提升效率。 当别人说你没有底线的时候&…

一文搞懂新型IO调度器BFQ简介

Linux io调度器有很多种&#xff0c;大多数调度器都经受住了各种市场环境的长时间验证&#xff0c;稳定性、性能得到各种用户的认可&#xff0c;但新的调度器依然展露头角&#xff0c;在4.12内核中出现了一个新的bfq调度器&#xff0c;这个调度器将取代曾经的辉煌的cfq调度器。…

Python3使用sys.argv和os.system 从一个程序调用另一个程序,并将参数传递

由于实验需要&#xff0c;需要从A.py 调用另一个B.py&#xff0c;并将A.py中的参数mean、max、min三个值传递给B。 这里参考了其他人的文章 http://t.csdn.cn/cQKio http://t.csdn.cn/QNqml http://t.csdn.cn/yEJeD 参考其他人的程序&#xff0c;发现其实很简单&#xff0c;…

ctfshow web入门代码审计 web301-305

1.web301 共有这几个文件 #checklogin.php <?php error_reporting(0); session_start(); require conn.php; $_POST[userid]!empty($_POST[userid])?$_POST[userid]:""; $_POST[userpwd]!empty($_POST[userpwd])?$_POST[userpwd]:""; $username$_PO…

LLVM编译器后端比较功能的添加

1.动机 从机器层面上来看&#xff0c;控制流类的跳转指令分为无条件跳转和有条件跳转&#xff0c;无条件跳转 JMP&#xff0c;有条件跳转 JEQ、JNE、JLT、JGT、JLE、JGE&#xff0c;这部分指令是需要通过检查 condition code &#xff08;SW 寄存器&#xff09;来决定跳转条件&…

解析基于Pytorch的残差神经网络(ResNet18模型),并使用数据集CIFAR10来进行预测与训练

解析基于Pytorch的残差神经网络&#xff08;ResNet18模型&#xff09;&#xff0c;并使用数据集CIFAR10来进行预测与训练 1.0、什么是残差神经网络 注&#xff1a;本人才疏学浅&#xff0c;如有纰漏&#xff0c;请不吝赐教 残差神经网络其实是与卷积神经网络分不开的&#x…

Java项目无法启动排查

Java项目无法启动排查 1.启动服务发现 无法写入日志也无法启动项目2.df查看磁盘占用情况 、free -h查看内存占用、top查看CPU使用率负载率3.此时磁盘满4.清理磁盘5.定时任务 1.启动服务发现 无法写入日志也无法启动项目 2.df查看磁盘占用情况 、free -h查看内存占用、top查看C…

计及源荷不确定性的综合能源生产单元运行调度与容量配置优化研究(Matlab代码实现)

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 ⛳️座右铭&a…

java贸易企业工作信息管理与利润返现系统sxA5进销存程序

目 录 摘 要 I Abstract II 第1章 绪论 1 1.1 课题背景 1 1.2 研究现状 1 本章小结 1 第2章 可行性分析 2 2.1 经济可行性 2 2.2 技术可行性 2 2.3 操作可行性 2 2.4 业务流程分析 3 本章小结 3 第3章 需求分析 4 3.1 需求分析 4 …

数据库基础篇 《3. 基本的SELECT语句》

目录 1. SQL概述 1.1 SQL背景知识 1.2 SQL语言排行榜 1.3 SQL 分类 2. SQL语言的规则与规范 2.1 基本规则 2.2 SQL大小写规范 &#xff08;建议遵守&#xff09; 2.3 注释 2.4 命名规则&#xff08;暂时了解&#xff09; 2.5 数据导入指令 3. 基本的SELECT语句 3.0…

【攻城狮计划】Renesas RA2E1 运行 命名

&#x1f6a9;WRITE IN FRONT&#x1f6a9; &#x1f50e;介绍&#xff1a;"謓泽"正在路上朝着"攻城狮"方向"前进四"&#x1f50e;&#x1f3c5;荣誉&#xff1a;2021|2022年度博客之星物联网与嵌入式开发TOP5|TOP4、2021|2022博客之星TOP10…

法大大合同批量下载

1.测试需求 法大大网上80万合同需要下载下来 其实总共1392392页,20885871万条合同数据要下载下来的 2.测试需求分析与验证 2.1调通接口,取到合同列表页信息 遇到的问题: 登录页面有图形验证码,不好处理 解决: 手动登录后用已经有的cookie,如果超时需要重新登录抓取co…

ChatGPT闲谈——火出圈的为什么是 OpenAI?

ChatGPT 走入大众视野之后&#xff0c;AIGC 行业迎来了爆发&#xff0c;尤其是上个月&#xff0c;仿佛每一天都可能是「历史性」的一天。 现在各大网站已经有非常多的优秀创作者进行总结和分析&#xff0c;都是值得一阅的好文。今天本文也分享了关于ChatGPT的看法&#xff0c;有…