李沐d2l(十一)--锚框

news/2024/5/20 15:30:37/文章来源:https://blog.csdn.net/qq_18824403/article/details/126668398

文章目录

    • 一、概念
    • 二、代码
      • 1 生成锚框
      • 2 IoU(交互比)
      • 3 将真实边界框分配给锚框
      • 4 标记类和偏移
      • 5 应用逆偏移变换来返回预测的边界框坐标
      • 6 nms
      • 7 将非极大值抑制应用于预测边界框

一、概念

在目标检测算法中,通常会在输入图像中采样大量的区域(生成多个边缘框),锚框就是从多个边缘框中判断最接近真实预测目标的区域。

整个过程分为两次预测:

  1. 类别:预测锚框中所含物体的类别
  2. 位置:预测锚框到边缘框的位置偏移

IoU-交叉比

IoU用来计算两个框之间的相似度:0 表示无重叠,1 表示重合。

image-20220902141422535

赋予锚框标号

在训练集中,将每个锚框视为一个训练样本,为了训练目标检测模型,需要每个锚框的类别和偏移量(真实边缘框相对于锚框的偏移量)标签。

在预测的时候,首先为每个图像生成多个锚框,预测所有锚框的类别和偏移量,根据预测的偏移量调整它们的位置以获得预测的边缘框,最后只输出符合特定条件的预测边缘框

过程

如下图所示,我们有4个边缘框,对应4个类别物体,每一列对应7个锚框。

image-20220902142634978

首先我们要求每个锚框与边缘框的IoU值,蓝色的代表已经算出IoU。假设M22是最大的IoU值,就说明锚框2的任务是去预测边缘框2,接下来把M22的行列删除,如右图。

现在M51是最大的IoU,同理说明锚框5的任务是去预测边缘框1。以此类推,直到所有的锚框都有了标号。

image-20220902143058884

非极大值抑制(NMS)输出

每个锚框都会预测一个边缘框,这些预测值之间可能存在比较相似的预测,NMS就是去合并相似的预测,让输出干净一点。

过程:

  1. 选中非背景的最大预测值
  2. 去掉所有其它和它IoU值大于θ的预测(也就是去掉和最大预测值相似度比较高的其它锚框)
  3. 重复上面过程直到所有预测要么被选中,要么被去掉

二、代码

1 生成锚框

以每个像素点为中心,生成高、宽不同的锚框。锚框的宽度和高度分别是ws(r)ws\sqrt(r)ws(r)hs/(r)hs/\sqrt(r)hs/(r),w和h是高、宽,s表示锚框占图片的大小,r是锚框的高宽比。一般的组合是(s1,r1),(s1,r2),...,(s1,rm),(s2,r1),(s3,r1),...,(sn,r1)(s1,r1),(s1,r2),...,(s1,rm),(s2,r1),(s3,r1),...,(sn,r1)(s1,r1),(s1,r2),...,(s1,rm),(s2,r1),(s3,r1),...,(sn,r1)

def multibox_prior(data, sizes, ratios):in_height, in_width = data.shape[-2:]device, num_sizes, num_ratios = data.device, len(sizes), len(ratios)boxes_per_pixel = (num_sizes + num_ratios - 1)size_tensor = torch.tensor(sizes, device=device)ratio_tensor = torch.tensor(ratios, device=device)offset_h, offset_w = 0.5, 0.5steps_h = 1.0 / in_heightsteps_w = 1.0 / in_widthcenter_h = (torch.arange(in_height, device=device) + offset_h) * steps_hcenter_w = (torch.arange(in_width, device=device) + offset_w) * steps_wshift_y, shift_x = torch.meshgrid(center_h, center_w)shift_y, shift_x = shift_y.reshape(-1), shift_x.reshape(-1)w = torch.cat((size_tensor * torch.sqrt(ratio_tensor[0]),sizes[0] * torch.sqrt(ratio_tensor[1:])))\* in_height / in_widthh = torch.cat((size_tensor / torch.sqrt(ratio_tensor[0]),sizes[0] / torch.sqrt(ratio_tensor[1:])))anchor_manipulations = torch.stack((-w, -h, w, h)).T.repeat(in_height * in_width, 1) / 2out_grid = torch.stack([shift_x, shift_y, shift_x, shift_y],dim=1).repeat_interleave(boxes_per_pixel, dim=0)output = out_grid + anchor_manipulationsreturn output.unsqueeze(0)

展示一个锚框

img = d2l.plt.imread('catdog.jpg')
h, w = img.shape[:2]  # 561 728
X = torch.rand(size=(1, 3, h, w))
Y = multibox_prior(X, sizes=[0.75, 0.5, 0.25], ratios=[1, 2, 0.5]) # torch.Size([1, 2042040, 4])
boxes = Y.reshape(h, w, 5, 4) # tensor([0.06, 0.07, 0.63, 0.82])def show_bboxes(axes, bboxes, labels=None, colors=None):"""显示所有边界框。"""def _make_list(obj, default_values=None):if obj is None:obj = default_valueselif not isinstance(obj, (list, tuple)):obj = [obj]return objlabels = _make_list(labels)colors = _make_list(colors, ['b', 'g', 'r', 'm', 'c'])for i, bbox in enumerate(bboxes):color = colors[i % len(colors)]rect = d2l.bbox_to_rect(bbox.detach().numpy(), color)axes.add_patch(rect)if labels and len(labels) > i:text_color = 'k' if color == 'w' else 'w'axes.text(rect.xy[0], rect.xy[1], labels[i], va='center',ha='center', fontsize=9, color=text_color,bbox=dict(facecolor=color, lw=0))d2l.set_figsize()
bbox_scale = torch.tensor((w, h, w, h))
fig = d2l.plt.imshow(img)
show_bboxes(fig.axes, boxes[250, 250, :, :] * bbox_scale, ['s=0.75, r=1', 's=0.5, r=1', 's=0.25, r=1', 's=0.75, r=2', 's=0.75, r=0.5'
])
d2l.plt.show()

image-20220902150359931

2 IoU(交互比)

def box_iou(boxes1, boxes2):"""计算两个锚框或边界框列表中成对的交并比。"""box_area = lambda boxes: ((boxes[:, 2] - boxes[:, 0]) *(boxes[:, 3] - boxes[:, 1]))areas1 = box_area(boxes1) # 算出锚框1的面积areas2 = box_area(boxes2) # 算出锚框2的面积inter_upperlefts = torch.max(boxes1[:, None, :2], boxes2[:, :2]) inter_lowerrights = torch.min(boxes1[:, None, 2:], boxes2[:, 2:])inters = (inter_lowerrights - inter_upperlefts).clamp(min=0)inter_areas = inters[:, :, 0] * inters[:, :, 1] # 交集框union_areas = areas1[:, None] + areas2 - inter_areas # 各自的面积减去交集return inter_areas / union_areas

3 将真实边界框分配给锚框

def assign_anchor_to_bbox(ground_truth, anchors, device, iou_threshold=0.5):num_anchors, num_gt_boxes = anchors.shape[0], ground_truth.shape[0]jaccard = box_iou(anchors, ground_truth)anchors_bbox_map = torch.full((num_anchors,), -1, dtype=torch.long,device=device)max_ious, indices = torch.max(jaccard, dim=1)anc_i = torch.nonzero(max_ious >= 0.5).reshape(-1)box_j = indices[max_ious >= 0.5]anchors_bbox_map[anc_i] = box_jcol_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_idxjaccard[:, box_idx] = col_discardjaccard[anc_idx, :] = row_discardreturn anchors_bbox_map

4 标记类和偏移

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 offsetdef 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() + 1assigned_bb[indices_true] = label[bb_idx, 1:]offset = offset_boxes(anchors, assigned_bb) * bbox_maskbatch_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)

在图像中绘制这些地面真相边界框和锚框

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]])fig = d2l.plt.imshow(img)
show_bboxes(fig.axes, ground_truth[:, 1:] * bbox_scale, ['dog', 'cat'], 'k')
show_bboxes(fig.axes, anchors * bbox_scale, ['0', '1', '2', '3', '4'])
d2l.plt.show()

image-20220902151354300

5 应用逆偏移变换来返回预测的边界框坐标

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

6 nms

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: breakiou = 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)

7 将非极大值抑制应用于预测边界框

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)predicted_bb = offset_inverse(anchors, offset_pred)keep = nms(predicted_bb, conf, nms_threshold)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] = -1class_id = class_id[all_id_sorted]conf, predicted_bb = conf[all_id_sorted], predicted_bb[all_id_sorted]below_min_idx = (conf < pos_threshold)class_id[below_min_idx] = -1conf[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)

最后的输出只保留了最大置信度的锚框

image-20220902152433894

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

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

相关文章

ELASTICSEARCH快速入门

1. ELASTICSEARCH 1、安装elastic searchdokcer中安装elastic search (1)下载ealastic search和kibana docker pull elasticsearch:7.6.2docker pull kibana:7.6.2 (2)配置 mkdir -p /mydata/elasticsearch/config 创建目录mkdir -p /mydata/elasticsearch/dataecho "…

fastapi+mongo+qlib:体系化构建AI量化投研平台

百天计划之第34篇&#xff0c;关于“AI量化投资研究平台”建设。 从今天开始要开始一条主线——就是开始搭建整个投研平台。 如果说8月开始是知识点的梳理&#xff0c;一些基础技术的准备&#xff08;以qlib和机器学习为核心&#xff09;&#xff0c;9月开始重点是“以解决真…

.NET Entity FrameWork 总结 ,在项目中用处个人感觉不大。适合初级用用,不涉及到与数据库通信。

更新数据 第一种&#xff1a; 先从数据库中取出数据&#xff0c;然后再更新字段。效率较低&#xff0c;需要2次数据库操作&#xff1b; Entities&#xff1a;就是EF实体数据模型 using (var db new Entities()) { var data db.Member.Find(5); data.Name “new name”; db.…

基于Springboot+vue的玩具销售商城网站 elementui

爱玩儿是所有孩子的天性。尤其是在婴幼儿阶段。选择一个好的玩具&#xff0c;不仅能够让孩子玩儿的开心&#xff0c;而且有助于孩子智力的开发。很多家长在选择玩具的时候&#xff0c;不知道选择什么样的玩具。且当前玩具市场的玩具鱼目混杂&#xff0c;种类繁多&#xff0c;而…

cmake和makefile区别和cmake指定编译器(cmake -G)

一 cmake和makefile区别 要说明区别,我们先要区分下面三类工具: 1.项目构建生成工具 首先cmake是项目构建生成工具,cmake的代码可以与平台系统和编译器无关。类似cmake的工具还有autotools、qmake、GN,其中qmake已基本由cmake替代。cmake下载地址 cmake.org.cn 也就是说cma…

1.初识jQuery

jQuery是JS的库&#xff0c;封装了原生JS的一些DOM方法&#xff0c;使JS用起来更方便 目录 1 下载jQuery 2 jQuery的基本使用方式 3 jQuery入口函数 1 下载jQuery jQuery官网 jQuery 点击这里进入下载页面&#xff0c;我当前的版本为 3.6.1&#xff0c;如果你想下载之…

2022极端高温!人工智能如何预测森林火灾?| 万物AI

&#x1f4a1; 作者&#xff1a;ShowMeAI编辑部 &#x1f4e2; 声明&#xff1a;版权所有&#xff0c;转载请联系平台与作者并注明出处 &#x1f4e2; 收藏ShowMeAI查看更多精彩内容 8月21日晚&#xff0c;重庆北碚区山火一路向国家级自然保护区缙云山方向蔓延。为守护家园&…

LabVIEW通过网络传输数据

LabVIEW通过网络传输数据 选择应用程序的联网功能时&#xff0c;最重要的因素是应用程序使用的通信模型。不同的通信模型具有不同的数据传输要求。下表列出了最常见的几种通信模型以及推荐功能。 通信模型 说明 范例 推荐联网功能 处理数据 传输最新数据&#xff0c;从一…

Vue模块语法上(插值指令过滤器计算属性-监听属性)

文章目录 一、插值 1&#xff09;文本 2&#xff09;html 3&#xff09;属性 4&#xff09;表达式 5&#xff09;class绑定 6&#xff09;style绑定 二、指令 1.v-if|v-else|v-else-if 2.v-show 3.v-for 4.v-bind 5.v-on 6.v-model 三、过滤器 全局过滤器 局部过滤器…

从零开始配置SSH密钥到github

最近电脑新环境&#xff0c;重新配置SSH 密钥链接GitHub 1 git安装 1.1 下载git 在官网下载git.exe 下载地址》 https://github.com/git-for-windows/git/releases/download/v2.37.3.windows.1/Git-2.37.3-64-bit.exe 1.2 安装git 双击运行程序&#xff0c;然后一直下一步…

for3.0测试题(必看)

for循环测试题:99乘法表11=112=2 22=413=3 23=6 33=914=4 24=8 34=12 44=1615=5 25=10 35=15 45=20 55=2516=6 26=12 36=18 46=24 56=30 66=3617=7 27=14 37=21 47=28 57=35 67=42 77=4918=8 28=16 38=24 48=32 58=40 68=48 78=56 88=6419=9 29=18 39=27 49=36 59=45 69=54 79…

彩虹女神跃长空,Go语言进阶之Go语言高性能Web框架Iris项目实战-用户系统EP03

前文再续&#xff0c;之前一篇我们已经配置好了数据库以及模板引擎&#xff0c;现在可以在逻辑层编写具体业务代码了&#xff0c;博客平台和大多数在线平台一样&#xff0c;都是基于用户账号体系来进行操作&#xff0c;所以我们需要针对用户表完成用户账号的CURD操作。 用户后…

Hadoop 3.x(入门)----【Hadoop概述】

Hadoop 3.x&#xff08;入门&#xff09;----【Hadoop概述】1. Hadoop是什么2. Hadoop发展历史&#xff08;了解&#xff09;3. Hadoop三大发行版本&#xff08;了解&#xff09;4. Hadoop优势&#xff08;4高&#xff09;5. Hadoop组成&#xff08;重点&#xff09;1. HDFS架构…

Express--获取URL中携带的查询参数、获取URL中的动态参数、获取URL中的动态参数

Express获取URL中携带的查询参数 通过req.query对象&#xff0c;可以访问到客户端查询字符串形式&#xff0c;发送给服务器参数 req.query默认是一个空对象客户端使用url的地址是?键值对&键值对(?namejs$age78)等这种查询字符串形式&#xff0c;发送到服务器的参数----…

Oracle P6 -SQLServer数据库乱码案例分享

此案例根据近几日根一盆友提到的问题分享总结 简单说下P6的基本参数 P6Version: Primavera P6 21.12.0Database: Microsoft SQLServer 2017Server : Windows Server 2016 问题描述&#xff1a; 在P6 Professional (桌面客户端) 中输入中文的内容&#xff0c;无论是EPS名称&a…

【云原生 • Kubernetes】kubernetes 核心技术 - 集群安全机制

本文导读一、集群安全机制概述1.认证2. 鉴权(授权)3. 准入控制二、RBAC 概述三、RBAC 角色绑定操作演示一、集群安全机制概述 要知道&#xff0c;访问 Kubernetes 集群必需要进行三个步骤&#xff0c;即&#xff1a; 认证鉴权(授权)准入控制 而这个访问过程均需经过 apiserver…

ArcGIS流域划分基础知识初学者课程

ArcGIS流域划分基础知识初学者课程 GIS 概念和 ArcGIS、ArcGIS Pro、ArcGIS Online 工具与分水岭划分示例简介 课程英文名&#xff1a;Learn the basics of GIS and use of ArcGIS softwar 此视频教程共5.0小时&#xff0c;中英双语字幕&#xff0c;画质清晰无水印&#xff…

Python QGIS 3自动化教程

Python QGIS 3自动化教程 将你的 QGIS 技能提升到一个新的水平 课程英文名&#xff1a;Automating QGIS 3.xx with Python 此视频教程共小时&#xff0c;中英双语字幕&#xff0c;画质清晰无水印&#xff0c;源码附件全 下载地址 百度网盘地址&#xff1a;https://pan.baid…

SpirngBoot+微服务SpringCloud——Eureka服务的注册(二)

一、Eureka注册中心 1.接续SpringCloud&#xff08;一&#xff09;中的实例。如果我们的user-server部署了多个实例&#xff0c;如图&#xff1a; order-service在发动远程调用的时候该如何得知user-service实例的ip地址和端口有多个user-service实例地址&#xff0c;order-…

如何使用西门子存储卡清除博途S7-1200的密码

摘要&#xff1a;本文介绍一种清除西门子博途S7-1200型PLC密码的方法&#xff0c;使用的是存储卡&#xff0c;参考的是官方文档&#xff0c;不用担心存储卡会不会报废&#xff0c;PLC会不会损害。 问题描述&#xff1a;放置很久的PLC&#xff0c;忘记密码&#xff0c;下载不了程…