13.4 目标检测锚框标注 & 非极大值抑制

这篇具有很好参考价值的文章主要介绍了13.4 目标检测锚框标注 & 非极大值抑制。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

锚框的形状计算公式

假设原图的高为H,宽为W
13.4 目标检测锚框标注 & 非极大值抑制,动手学深度学习(计算机视觉篇),目标检测,人工智能,计算机视觉

锚框形状详细公式推导

13.4 目标检测锚框标注 & 非极大值抑制,动手学深度学习(计算机视觉篇),目标检测,人工智能,计算机视觉

以每个像素为中心生成不同形状的锚框

13.4 目标检测锚框标注 & 非极大值抑制,动手学深度学习(计算机视觉篇),目标检测,人工智能,计算机视觉

# s是缩放比,ratio是宽高比
def multibox_prior(data, sizes, ratios):
    """生成以每个像素为中心具有不同形状的锚框"""
    in_height,in_width = data.shape[-2:] # 取出最后两个元素,即h和w
    device,num_sizes,num_ratios = data.device,len(sizes),len(ratios)
    boxes_per_pixel = (num_sizes+num_ratios -1) # 以某个像素坐标为中心的锚框为n+m-1
    size_tensor = torch.tensor(sizes,device=device) # 将缩放比例列表sizes转为tensor, device参数指定设备
    ratio_tensor = torch.tensor(ratios,device=device)

    # 为了将锚点移动到像素的中心,需要设置偏移量。
    # 因为一个像素的高为1且宽为1,我们选择偏移我们的中心0.5
    offset_h, offset_w = 0.5, 0.5
    steps_h = 1.0 / in_height # 在y轴上缩放步⻓
    steps_w = 1.0 / in_width # 在x轴上缩放步⻓
    print(f'steps_h,steps_w = {steps_h,steps_w}')

    # 生成锚框的所有中心点
    center_h = (torch.arange(in_height, device=device) + offset_h) * steps_h
    center_w = (torch.arange(in_width, device=device) + offset_w) * steps_w
    print(f'center_h,center_w={center_h,center_w}')

    #网格化中心点坐标
    shift_y,shift_x = torch.meshgrid(center_h,center_w)
    #reshape成一维,shift_y和shift_x坐标一一对应
    shift_y,shift_x = shift_y.reshape(-1),shift_x.reshape(-1)
    print(f'shift_y, shift_x={shift_y, shift_x}') #

     #norm=√(H/W),这个就是个标号,方便计算
    norm = torch.sqrt(torch.tensor(in_height)/torch.tensor(in_width))

    # 生成“boxes_per_pixel”个高和宽,
    #只考虑包含s1或r1的组合,因此S*r1 与s1*R合并即为n+m-1个锚框
    w = torch.cat((size_tensor * torch.sqrt(ratio_tensor[0]),
                   size_tensor[0] * torch.sqrt(ratio_tensor[1:]))) * norm
    h = torch.cat((size_tensor / torch.sqrt(ratio_tensor[0]),
                   size_tensor[0] / torch.sqrt(ratio_tensor[1:]))) / norm

    # 获得归一化后的锚框的w,h的一半,形成偏移量,为了让归一化后的锚框根据中心点 + 偏移量找到 左上角和右下角坐标
    anchor_manipulations = torch.stack((-w, -h, w, h)).T.repeat(in_height * in_width, 1) / 2
    # 每个中心点都将有“boxes_per_pixel”个锚框,
    # 所以生成含所有锚框中心的网格,重复了“boxes_per_pixel”次
    out_grid = torch.stack([shift_x, shift_y, shift_x, shift_y],dim=1).repeat_interleave(boxes_per_pixel, dim=0)

      # 每个中心点都将有“boxes_per_pixel”个锚框,
    # 所以生成含所有锚框中心的网格,重复了“boxes_per_pixel”次
    out_grid = torch.stack([shift_x, shift_y, shift_x, shift_y],dim=1).repeat_interleave(boxes_per_pixel, dim=0)
    #(x_min,y_min,x_max,y_max) =  归一化后的锚框中心点 + 往左上角和右下角走的偏移量
    output = out_grid + anchor_manipulations
    return output.unsqueeze(0)
# 将锚框变量Y的形状更改为(图像高度,图像宽度,以同一像素为中心的锚框的数量,4)
boxes = Y.reshape(h, w, 5, 4)#                                                  此处的5由 缩放的数量n + 宽高比的数量m -1 而得
# 访问以(250,250)为中心的第一个锚框。它有四个元素:锚框左上⻆的(x, y)轴坐标和右下⻆的(x, y)轴坐标
boxes[250, 250, 0, :] # 输出的坐标是归一化后的,即归一化前的锚框 w/in_weight 和 h/in_height
img = d2l.plt.imread('../data/images/cat_and_dog.jpg')
h, w = img.shape[:2]
print(h, w)
X = torch.rand(size=(1, 3, h, w))
# 返回的锚框变量Y的形状是(批量大小,锚框的数量,4 (表示锚框的左上角右下角坐标))。
Y = multibox_prior(X, sizes=[0.75, 0.5, 0.25], ratios=[1, 2, 0.5])
Y.shape

根据真实框来标注生成的锚框

13.4 目标检测锚框标注 & 非极大值抑制,动手学深度学习(计算机视觉篇),目标检测,人工智能,计算机视觉
13.4 目标检测锚框标注 & 非极大值抑制,动手学深度学习(计算机视觉篇),目标检测,人工智能,计算机视觉

# 计算IOU
def box_iou(boxes1,boxes2):
    '''
    :param boxes1: shape = (boxes1的数量,4)
    :param boxes2: shape = (boxes2的数量,4)
    :param areas1: boxes1中每个框的面积 ,shape = (boxes1的数量)
    :param areas2: boxes2中每个框的面积 ,shape = (boxes2的数量)
    :return:
    '''
    # 定义一个Lambda函数,输入boxes,内容是计算得到框的面积
    box_area = lambda  boxes:((boxes[:,2] - boxes[:,0]) * (boxes[:,3] - boxes[:,0]))
    # 计算面积
    areas1 = box_area(boxes1)
    areas2 = box_area(boxes2)
    # 计算交集 要把所有锚框的左上角坐标 与 真实框的所有左上角坐标 作比较,大的就是交集的左上角 ,加个None 可以让锚框与所有真实框作对比
    inter_upperlefts = torch.max(boxes1[:,None,:2],boxes2[:,:2])
    # 把所有锚框的右下角坐标 与 真实框的所有右下角坐标 作比较,小的就是交集的右下角坐标 ,加个None 可以让锚框与所有真实框作对比
    inter_lowerrights = torch.min(boxes1[:,None,2:],boxes2[:,2:])
    # 如果右下角-左上角有元素小于0,那就说明没有交集,clamp(min-0)会将每个元素与0比较,小于0的元素将会被替换成0
    inters = (inter_lowerrights - inter_upperlefts).clamp(min=0) # 得到w和h
    inter_areas = inters[:,:,0] * inters[:,:,1] # 每个样本的 w*h

    # 求锚框与真实框的并集
    # 将所有锚框与真实框相加,他们会多出来一个交集的面积,所以要减一个交集的面积
    union_areas = areas1[:,None] * areas2 - inter_areas
    return inter_areas/union_areas
# 每个真实框都要跟所有锚框计算iou,Iou数量等于,真实框数量 * 锚框的数量
def assign_anchor_to_bbox(ground_truth,anchors,devices,iou_threshold=0.5):
    # 得到锚框和真实框的个数
    num_anchors,num_gt_boxes = anchors.shape[0],ground_truth.shape[0]
    # jaccard是计算 所有锚框anchors和真实框ground_truth的交并比
    jaccard = box_iou(anchors,ground_truth)
    # torch.full(size,fill_value,dtype,device),如下代码生产成一个一位数组,长度为锚框的个数,值为-1
    anchors_bbox_map = torch.full((num_anchors,),-1,dtype=torch.long,device=devices)

    # 对行取最大值,得到每个真实框对应的最大IOU的锚框
    max_ious,indices = torch.max(jaccard,dim=1)
    # 返回张量中非0元素的索引,即Max_iou>设定的阈值,位于第i行和第j列的元素x_ij是锚框i和真实边界框j的IoU
    anc_i = torch.nonzero(max_ious>=iou_threshold).reshape(-1)
    box_j = indices[max_ious>=iou_threshold]
    anchors_bbox_map[anc_i] = box_j
    col_discard = torch.full((num_anchors,), -1)
    row_discard = torch.full((num_gt_boxes,), -1)
    for _ in range(num_gt_boxes):
        max_idx = torch.argmax(jaccard)
        box_idx = (max_idx % num_gt_boxes).long()
        anc_idx = (max_idx / num_gt_boxes).long()
        anchors_bbox_map[anc_idx] = box_idx
        jaccard[:, box_idx] = col_discard
        jaccard[anc_idx, :] = row_discard
    return anchors_bbox_map
# 标注类别和偏移量
def offset_boxes(anchors, assigned_bb, eps=1e-6):
    """对锚框偏移量的转换"""
    c_anc = d2l.box_corner_to_center(anchors)
    c_assigned_bb = d2l.box_corner_to_center(assigned_bb)
    offset_xy = 10 * (c_assigned_bb[:, :2] - c_anc[:, :2]) / c_anc[:, 2:]
    offset_wh = 5 * torch.log(eps + c_assigned_bb[:, 2:] / c_anc[:, 2:])
    offset = torch.cat([offset_xy, offset_wh], axis=1)
    return offset
'''
    如果一个锚框没有被分配真实边界框,将锚框的类别标记为背景。背景类别的锚框通常被称为负类锚框,其余的被称为正类锚框。
    我们使用真实边界框(labels参数)实现以下multibox_target函数,来标记锚框的类别和偏移量(anchors参数)。
    此函数将背景类别的索引设置为零,然后将新类别的整数索引递增一。
'''
def multibox_target(anchors, labels):
    """使用真实边界框标记锚框"""
    batch_size, anchors = labels.shape[0], anchors.squeeze(0)
    batch_offset, batch_mask, batch_class_labels = [], [], []
    device, num_anchors = anchors.device, anchors.shape[0]
    for i in range(batch_size):
        label = labels[i, :, :]
        anchors_bbox_map = assign_anchor_to_bbox(
            label[:, 1:], anchors, device)
        bbox_mask = ((anchors_bbox_map >= 0).float().unsqueeze(-1)).repeat(1, 4)
        # 将类标签和分配的边界框坐标初始化为零
        class_labels = torch.zeros(num_anchors, dtype=torch.long,
        device=device)
        assigned_bb = torch.zeros((num_anchors, 4), dtype=torch.float32,
        device=device)
        # 使用真实边界框来标记锚框的类别。
        # 如果一个锚框没有被分配,标记其为背景(值为零)
        indices_true = torch.nonzero(anchors_bbox_map >= 0)
        bb_idx = anchors_bbox_map[indices_true]
        class_labels[indices_true] = label[bb_idx, 0].long() + 1
        assigned_bb[indices_true] = label[bb_idx, 1:]
        # 使用真实边界框来标记锚框的类别。
        # 如果一个锚框没有被分配,标记其为背景(值为零)
        indices_true = torch.nonzero(anchors_bbox_map >= 0)
        bb_idx = anchors_bbox_map[indices_true]
        class_labels[indices_true] = label[bb_idx, 0].long() + 1
        assigned_bb[indices_true] = label[bb_idx, 1:]
        # 偏移量转换
        offset = offset_boxes(anchors, assigned_bb) * bbox_mask
        batch_offset.append(offset.reshape(-1))
        batch_mask.append(bbox_mask.reshape(-1))
        batch_class_labels.append(class_labels)

    bbox_offset = torch.stack(batch_offset)
    bbox_mask = torch.stack(batch_mask)
    class_labels = torch.stack(batch_class_labels)
    return (bbox_offset, bbox_mask, class_labels)
# 第一个元素表示类别,0代表狗,1代表猫。其余四个元素是左下角坐标和右上角坐标(归一化后的介于0-1之间),归一化的方法是,x坐标 / 宽,y坐标/高
ground_truth = torch.tensor([[0, 0.1, 0.08, 0.52, 0.92],
                             [1, 0.55, 0.2, 0.9, 0.88]])
# 锚框
anchors = torch.tensor([[0, 0.1, 0.2, 0.3], [0.15, 0.2, 0.4, 0.4],
                        [0.63, 0.05, 0.88, 0.98], [0.66, 0.45, 0.8, 0.8],
                        [0.57, 0.3, 0.92, 0.9]])
bbox_scale = torch.tensor((w, h, w, h))
# img = d2l.plt.imread('../data/images/cat_dog.png')
img = d2l.plt.imread('../data/images/cat_and_dog.jpg')
fig = d2l.plt.imshow(img)
# 画出真实框 :(坐标轴,归一化*bbox_scale得到原图规模的坐标,标签,颜色)
show_bboxes(fig.axes,ground_truth[:,1:] * bbox_scale,['dog','cat'],'k') # k最后画出来是黑色
# 画出设置的锚框,把锚框类别标记为0-4
show_bboxes(fig.axes, anchors * bbox_scale, ['0', '1', '2', '3', '4']);
'''
    labels[0]:
    labels[1]:掩码,形状为(批量大小,锚框数的4倍),对应每个锚框的4个偏移量(负类掩码为0),通过元素乘法,将负类的偏移量过滤掉
    labels[2]:锚框对应的标签
'''
labels = multibox_target(anchors.unsqueeze(dim=0),ground_truth.unsqueeze(dim=0))

非极大值抑制

13.4 目标检测锚框标注 & 非极大值抑制,动手学深度学习(计算机视觉篇),目标检测,人工智能,计算机视觉文章来源地址https://www.toymoban.com/news/detail-671800.html

'''
    在预测时,我们先为图像生成多个锚框,再为这些锚框一一预测类别和偏移量。一个预测好的边界框则根据其中某个带有预测偏移量的锚框而生成。下面我们实现了offset_inverse函数,该函数将锚框和偏移量预测作为输入,并应用逆偏移变换来返回预测的边界框坐标。
    输入: 锚框 和 偏移量预测
    输出:根据锚框的原始坐标和预测的偏移量 计算出的 预测的边界框坐标
'''
def offset_inverse(anchors, offset_preds):
    """根据带有预测偏移量的锚框来预测边界框"""
    anc = d2l.box_corner_to_center(anchors)
    pred_bbox_xy = (offset_preds[:, :2] * anc[:, 2:] / 10) + anc[:, :2]
    pred_bbox_wh = torch.exp(offset_preds[:, 2:] / 5) * anc[:, 2:]
    pred_bbox = torch.cat((pred_bbox_xy, pred_bbox_wh), axis=1)
    predicted_bbox = d2l.box_center_to_corner(pred_bbox)
    return predicted_bbox
'''按降序对置信度进行排序并返回其索引'''
#@save
def nms(boxes, scores, iou_threshold):
    """对预测边界框的置信度进行排序"""
    B = torch.argsort(scores, dim=-1, descending=True)
    keep = []
    # 保留预测边界框的指标
    while B.numel() > 0:
        i = B[0]
        keep.append(i)
        if B.numel() == 1: break
        iou = box_iou(boxes[i, :].reshape(-1, 4),
                      boxes[B[1:], :].reshape(-1, 4)).reshape(-1)
        inds = torch.nonzero(iou <= iou_threshold).reshape(-1)
        B = B[inds + 1]
    return torch.tensor(keep, device=boxes.device)
def multibox_detection(cls_probs, offset_preds, anchors, nms_threshold=0.5,pos_threshold=0.009999999):
    """使用非极大值抑制来预测边界框"""
    device, batch_size = cls_probs.device, cls_probs.shape[0]
    anchors = anchors.squeeze(0)
    num_classes, num_anchors = cls_probs.shape[1], cls_probs.shape[2]
    out = []
    for i in range(batch_size):
        cls_prob, offset_pred = cls_probs[i], offset_preds[i].reshape(-1, 4)
        conf, class_id = torch.max(cls_prob[1:], 0)
        
        '''调用offset_inverse'''
        predicted_bb = offset_inverse(anchors, offset_pred)
        
        '''调用nms'''
        keep = nms(predicted_bb, conf, nms_threshold)
        
        # 找到所有的non_keep索引,并将类设置为背景
        all_idx = torch.arange(num_anchors, dtype=torch.long, device=device)
        combined = torch.cat((keep, all_idx))
        uniques, counts = combined.unique(return_counts=True)
        non_keep = uniques[counts == 1]
        all_id_sorted = torch.cat((keep, non_keep))
        class_id[non_keep] = -1
        class_id = class_id[all_id_sorted]
        conf, predicted_bb = conf[all_id_sorted], predicted_bb[all_id_sorted]
        # pos_threshold是一个用于非背景预测的阈值

        below_min_idx = (conf < pos_threshold)
        class_id[below_min_idx] = -1
        conf[below_min_idx] = 1 - conf[below_min_idx]
        pred_info = torch.cat((class_id.unsqueeze(1),
                               conf.unsqueeze(1),
                               predicted_bb), dim=1)
        out.append(pred_info)
    return torch.stack(out)

到了这里,关于13.4 目标检测锚框标注 & 非极大值抑制的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • 图像处理之canny边缘检测(非极大值抑制和高低阈值)

    Canny算子是John F.Canny 大佬在1986年在其发表的论文 《Canny J. A computational approach to edge detection [J]. IEEE Transactions on Pattern Analysis and Machine Intelligence, 1986 (6): 679-698.》提出来的。 低错误率。所有边缘都应该被找到,并且应该没有伪响应。也就是检测到的边缘必须尽可能时真实的边缘

    2024年02月16日
    浏览(31)
  • YOLO等目标检测模型的非极大值抑制NMS和评价指标(Acc, Precision, Recall, AP, mAP, RoI)、YOLOv5中mAP@0.5与mAP@0.5:0.95的含义

    YOLOv5正负样本定义 yolov5输出有3个预测分支,每个分支的每个网格有3个anchor与之对应。 没有采用IOU最大的匹配方法,而是通过计算该bounding-box和当前层的anchor的宽高比,如果最大比例大于4(设定阈值),则比例过大,则说明匹配度不高,将该bbox过滤,在当前层认为是背景

    2024年02月03日
    浏览(36)
  • YOLO物体检测-系列教程1:YOLOV1整体解读(预选框/置信度/分类任/回归任务/损失函数/公式解析/置信度/非极大值抑制)

    YOLOV1整体解读 YOLOV2整体解读 YOLOV1提出论文:You Only Look Once: Unified, Real-Time Object Detection two-stage(两阶段):Faster-rcnn Mask-Rcnn系列 one-stage(单阶段):YOLO系列 最核心的优势:速度非常快,适合做实时检测任务! 但是缺点也是有的,效果通常情况下不会太好! 机器学习 分类任

    2024年02月09日
    浏览(31)
  • openCV实战-系列教程5:边缘检测(Canny边缘检测/高斯滤波器/Sobel算子/非极大值抑制/线性插值法/梯度方向/双阈值检测 )、原理解析、源码解读 ?????OpenCV实战系列总目录

    打印一个图片可以做出一个函数: Canny是一个科学家在1986年写了一篇论文,所以用自己的名字来命名这个检测算法,Canny边缘检测算法这里写了5步流程,会用到之前《openCV实战-系列教程》的内容。  使用高斯滤波器,以平滑图像,滤除噪声。 计算图像中每个像素点的梯度强

    2024年02月11日
    浏览(39)
  • 极值理论(一):极大值极限分布

    1 为什么引入广义极值分布:         考虑随机变量序列极大值分布:,当时,不一定是依分布收敛的(一般我们总是期望它是收敛的)。因此,我们引入广义极值分布来描述标准化。 2 广义极值分布(GEV): 对于标准化有  =0:Gumbel分布;0:Frechet分布;0:weibull分布 何谓

    2024年02月05日
    浏览(34)
  • 非极大值抑制(NMS)算法详解

    百度飞桨(PaddlePaddle) - PP-OCRv3 文字检测识别系统 预测部署简介与总览 百度飞桨(PaddlePaddle) - PP-OCRv3 文字检测识别系统 Paddle Inference 模型推理(离线部署) 百度飞桨(PaddlePaddle) - PP-OCRv3 文字检测识别系统 基于 Paddle Serving快速使用(服务化部署 - CentOS) 百度飞桨(PaddlePaddle) - PP

    2024年02月06日
    浏览(29)
  • PTA 7-2 求矩阵的局部极大值

    给定M行N列的整数矩阵A,如果A的非边界元素A[i][j]大于相邻的上下左右4个元素,那么就称元素A[i][j]是矩阵的局部极大值。本题要求给定矩阵的全部局部极大值及其所在的位置。 输入格式: 输入在第一行中给出矩阵A的行数M和列数N(3≤M,N≤20);最后M行,每行给出A在该行的

    2024年02月04日
    浏览(32)
  • 春招面试准备笔记——NMS(非极大值抑制)算法

    NMS(非极大值抑制)算法非极大值抑制是用于减少物体检测算法中重叠边界框或区域的数量的技术。通过对每个类别的检测框按置信度排序,然后逐个遍历,保留置信度最高的框,并抑制与其重叠且置信度低的框,从而得到更准确和简洁的检测结果。 假设我们使用一个人脸检

    2024年02月21日
    浏览(45)
  • 【NMS,非极大值抑制】Python和C++的实现

    代码如下:

    2024年02月15日
    浏览(24)
  • 非极大值抑制详细原理(NMS含代码及详细注释)

    作者主页: 爱笑的男孩。的博客_CSDN博客-深度学习,YOLO,活动领域博主 爱笑的男孩。擅长深度学习,YOLO,活动,等方面的知识,爱笑的男孩。关注算法,python,计算机视觉,图像处理,深度学习,pytorch,神经网络,opencv领域. https://blog.csdn.net/Code_and516?type=collect 个人介绍:打工人。 分享内容

    2023年04月21日
    浏览(40)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包