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

锚框的形状计算公式

假设原图的高为H,宽为W
在这里插入图片描述

锚框形状详细公式推导

在这里插入图片描述

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

请添加图片描述

# 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

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

请添加图片描述
请添加图片描述

# 计算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))

非极大值抑制

请添加图片描述

'''
    在预测时,我们先为图像生成多个锚框,再为这些锚框一一预测类别和偏移量。一个预测好的边界框则根据其中某个带有预测偏移量的锚框而生成。下面我们实现了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)

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

windows安装新openssl后依然显示旧版本

1、Windows环境下升级openssl后&#xff0c;通过指令openssl version -a查看版本号&#xff1a; 这个版本号是以前的老版本&#xff0c;不知道在哪里 2、网上找了老半天也没找到答案&#xff0c;最后通过指令 where openssl 才找到原来的openssl在哪里&#xff0c;把老的卸载掉…

ASEMI快恢复二极管APT80DQ20BG封装尺寸

编辑-Z APT80DQ20BG参数描述&#xff1a; 型号&#xff1a;APT80DQ20BG 最大峰值反向电压(VRRM)&#xff1a;200V 最大直流阻断电压VR(DC)&#xff1a;200V 平均整流正向电流(IF)&#xff1a;80A 非重复峰值浪涌电流(IFSM)&#xff1a;600A 工作接点温度和储存温度(TJ, …

使用VisualStudio制作上位机(二)

文章目录 使用VisualStudio制作上位机(二)第三部分:GUI内部函数设计使用VisualStudio制作上位机(二) Author:YAL 第三部分:GUI内部函数设计 事件添加 给窗体或窗体按钮相关的操作添加事件有两种方式,事件的名字直白的表面了这是什么事件。 直接双击界面,自动生成窗…

SocketTools.NET 11.0.2148.1554 Crack

添加新功能以简化使用 URL 建立 TCP 连接的过程。 2023 年 8 月 23 日 - 12:35新版本 特征 添加了“HttpGetTextEx”函数&#xff0c;该函数在返回字符串缓冲区中的文本内容时提供附加选项。添加了对“FileTransfer”.NET 类和 ActiveX 控件中的“GetText”和“PutText”方法的…

python模拟登入某平台+破解验证码

概述 python模拟登录平台&#xff0c;遇见验证码识别&#xff01;用最简单的方法seleniumda破解验证码&#xff0c;来自动登录平台 详细 python用seleniumxpath模拟登录破解验证码 先随便找个小说平台用户登陆 - 书海小说网用户登陆 - 书海小说网用户登陆 - 书海小说网 准…

2023年8月22日OpenAI推出了革命性更新:ChatGPT-3.5 Turbo微调和API更新,为您的业务量身打造AI模型

&#x1f337;&#x1f341; 博主猫头虎 带您 Go to New World.✨&#x1f341; &#x1f984; 博客首页——猫头虎的博客&#x1f390; &#x1f433;《面试题大全专栏》 文章图文并茂&#x1f995;生动形象&#x1f996;简单易学&#xff01;欢迎大家来踩踩~&#x1f33a; &a…

【Spring Boot】详解条件注解以及条件拓展注解@Conditional与@ConditionalOnXxx

Spring Conditional Spring 4.0提供的注解。作用是给需要装载的Bean增加一个条件判断。只有满足条件才会装在到IoC容器中。而这个条件可以由自己去完成的&#xff0c;可以通过重写Condition接口重写matches()方法去实现自定义的逻辑。所以说这个注解增加了对Bean装载的灵活性。…

【肌电图信号分析】通道肌电图并查找收缩周期的数量、振幅、最大值和持续时间(Matlab代码实现)

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

在本地搭建Jellyfin影音服务器,支持公网远程访问影音库的方法分享

文章目录 1. 前言2. Jellyfin服务网站搭建2.1. Jellyfin下载和安装2.2. Jellyfin网页测试 3.本地网页发布3.1 cpolar的安装和注册3.2 Cpolar云端设置3.3 Cpolar本地设置 4.公网访问测试5. 结语 1. 前言 随着移动智能设备的普及&#xff0c;各种各样的使用需求也被开发出来&…

threejs贴图系列(一)canvas贴图

threejs不仅支持各种texture的导入生成贴图&#xff0c;还可以利用canvas绘制图片作为贴图。这就用到了CanvasTexture&#xff0c;它接受一个canas对象。只要我们绘制好canvas&#xff0c;就可以作为贴图了。这里我们利用一张图片来实现这个效果。 基础代码&#xff1a; impo…

sizeof和strlen的对比

文章目录 &#x1f6a9;前言&#x1f6a9;sizeof&#x1f6a9;strlen&#x1f6a9;sizeof和strlen对比 &#x1f6a9;前言 很多小白在学习中&#xff0c;经常将sizeof和strlen弄混了。本篇文章&#xff0c;小编讲解一下sizeof和strlen的区别。&#x1f937;‍♂️ &#x1f6a9…

分享好用的翻译软件

网易有道翻译→网易有道翻译

npm install 安装依赖,报错 Host key verification failed

设置 git 的身份和邮箱 git config --global user.name "你的名字" > 用户名 git config --global user.email “你的邮箱" > 邮箱进入 > 用户 > [你的用户名] > .ssh文件夹下,删除 known_hosts 文件即可 进入之后有可能会看到 known_hosts…

css实现文字的渐变,适合大屏

1 在全局写一个全局样式&#xff0c;文字渐变 2 在组件中使用 CSS3利用-webkit-background-clip: text;实现文字渐变效果_css如何把盒子底部的文字变成透明渐变_I俩月亮的博客-CSDN博客 CSS 如何实现文字渐变色 &#xff1f;_css字体颜色渐变_一个水瓶座程序猿.的博客-CSDN博客…

docker 安装 redis

目录 1、下载镜像文件 2、创建实例并启动 3、使用 redis 镜像执行 redis-cli 命令连接 4、redis持久化操作 5、然后按照第3点&#xff0c;再试一试&#xff0c;看看redis持久化是否配置成功。 6、最后与redis可视化工具测试连接 大家先 su root&#xff0c;这让输入命令就…

goland 中的调试器 -- Evaluate

今天一个好朋友 找到我&#xff0c;问我关于goland中Evaluate 小计算器的使用方式&#xff0c;说实话&#xff0c;我在此之前也没用过这个东西&#xff0c;然后我就找一些相关文档&#xff0c;但是这类文档少的可怜&#xff0c;所以我就稍微研究一下&#xff0c;找找材料&#…

【QT5-自我学习-线程qThread移植与使用-通过代码完成自己需要功能-移植小记3】

【QT5-自我学习-线程qThread移植与使用-通过代码完成自己需要功能-移植小记3】 1、前言2、实验环境3、自我总结&#xff08;1&#xff09;文件的编写&#xff08;2&#xff09;信号与槽的新理解&#xff08;3&#xff09;线程数据的传递 4、移植步骤第一步&#xff1a;添加新文…

华为云Stack的学习(一)

一、华为云Stack架构 1.HCS 物理分散、逻辑统一、业务驱动、运管协同、业务感知 2.华为云Stack的特点 可靠性 包括整体可靠性、数据可靠性和单一设备可靠性。通过云平台的分布式架构&#xff0c;从整体系统上提高可靠性&#xff0c;降低系统对单设备可靠性的要求。 可用性…

2023年国赛 高教社杯数学建模思路 - 案例:退火算法

文章目录 1 退火算法原理1.1 物理背景1.2 背后的数学模型 2 退火算法实现2.1 算法流程2.2算法实现 建模资料 ## 0 赛题思路 &#xff08;赛题出来以后第一时间在CSDN分享&#xff09; https://blog.csdn.net/dc_sinor?typeblog 1 退火算法原理 1.1 物理背景 在热力学上&a…

Windows10批处理命令行设置环境变量笔记,无需重新安装python与chrome

近期&#xff0c;工作中经常安装、部署python生产、开发环境&#xff0c;比较麻烦&#xff0c;也没有心情去优化。突然&#xff0c;我的电脑崩溃了&#xff0c;在重新安装电脑的过程中&#xff0c;保留了原来的安装软件&#xff08;有的没有放在系统盘中&#xff09;&#xff0…