目标检测中生成锚框函数详解

python 复制代码
%matplotlib inline
import torch
from d2l import torch as d2l
torch.set_printoptions(2) # 让pytorch打印张量时,只打印到小数点后两位

将设一张图片,宽和高为2,2

python 复制代码
X = torch.rand(size=(1,3,2,2))
Y = generate_anchors(X,sizes=[0.75,0.5,0.25],ratios=[1,2,0.5])

锚框中心点的设置

python 复制代码
# 为每个像素可以生成 n+m-1个锚框,整个图像生成 wh(n+m-1)
def generate_anchors(data,sizes,ratios): # 书上的名字是 multibox_prior
    '''
    data:输入图像,sizes:缩放比 rations:宽高比
    :return: (批量数,锚框数量,4)
    '''
    '''1.数据准备'''
    # 图片的shape为(样本数,h,w),取出图片的h,w
    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)
    # 把缩放列表和宽高比列表转换为tensor格式
    size_tensor = torch.tensor(sizes,device=device)
    ratio_tensor = torch.tensor(ratios,device=device)

    '''设置锚框中心坐标 和 步长'''
    # 因为1像素的宽和高都是1,所以1像素的中心点是(0.5,0.5)
    offset_h,offset_w=0.5,0.5
    # 缩放步长
    steps_h = 1/in_height
    steps_w = 1/in_width
python 复制代码
	# 不乘以步长,垂直方向上锚框的中心点
	center_h = (torch.arange(in_height,device=device) + offset_h)
	print(center_h)

tensor([0.50, 1.50])

python 复制代码
    # 乘以步长时,垂直方向上锚框的中心点。
    center_h = (torch.arange(in_height,device=device) + offset_h) * steps_h
    print(center_h)

tensor([0.25, 0.75])

python 复制代码
	# 不乘以步长,水平方向上锚框的中心点
	center_w = (torch.arange(in_width,device=device) + offset_w)
	print(center_w)

tensor([0.50, 1.50])

python 复制代码
	# 乘以步长,水平方向上锚框的中心点
	center_w = (torch.arange(in_width,device=device) + offset_w) * steps_w
	print(center_w)

tensor([0.25, 0.75])

乘以步长和不乘步长,锚框中心点的区别

之所以要乘以步长,是为了对应/w,/h归一化后的锚框形状。


python 复制代码
	# 生成锚框的所有中心点
	shift_y,shift_x = torch.meshgrid(center_h,center_w)
	print(f'shift_y = {shift_y}')
	print(f'shift_x = {shift_x}')

shift_y = tensor([[0.25, 0.25], [0.75, 0.75]])

shift_x = tensor([[0.25, 0.75], [0.25, 0.75]])

python 复制代码
 #把tensor变成一维
	shift_y,shift_x = shift_y.reshape(-1),shift_x.reshape(-1)
	print(shift_y, shift_x)

tensor([0.25, 0.25, 0.75, 0.75]) tensor([0.25, 0.75, 0.25, 0.75])

参考链接

https://zhuanlan.zhihu.com/p/455807888

相关推荐
飞哥数智坊1 小时前
GPT-5-Codex 发布,Codex 正在取代 Claude
人工智能·ai编程
倔强青铜三1 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
虫无涯2 小时前
Dify Agent + AntV 实战:从 0 到 1 打造数据可视化解决方案
人工智能
Dm_dotnet4 小时前
公益站Agent Router注册送200刀额度竟然是真的
人工智能
算家计算4 小时前
7B参数拿下30个世界第一!Hunyuan-MT-7B本地部署教程:腾讯混元开源业界首个翻译集成模型
人工智能·开源
机器之心4 小时前
LLM开源2.0大洗牌:60个出局,39个上桌,AI Coding疯魔,TensorFlow已死
人工智能·openai
Juchecar6 小时前
交叉熵:深度学习中最常用的损失函数
人工智能
林木森ai6 小时前
爆款AI动物运动会视频,用Coze(扣子)一键搞定全流程(附保姆级拆解)
人工智能·aigc
聚客AI6 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
BeerBear8 小时前
【保姆级教程-从0开始开发MCP服务器】一、MCP学习压根没有你想象得那么难!.md
人工智能·mcp