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

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

相关推荐
百度Geek说6 分钟前
都在开源 Harness,Codex 和 DeepSeek 到底有什么不一样?
人工智能
科研小牛马9 分钟前
北航何静:AI时代,热门专业十年后怎么样了
人工智能
weixin_4462608513 分钟前
JarvisGUI:面向跨设备GUI智能体的动态任务组合评测基准
人工智能
Splashtop高性能远程控制软件17 分钟前
AI 辅助端点运维先接手补丁分级、合规可视和同台处置
运维·网络·人工智能·自动化·远程工作·splashtop
Yanjun2i25 分钟前
Agent学习记录四:多工具时如何处理
人工智能·python·学习·agent
creator_Li29 分钟前
深度学习 学习笔记
pytorch·深度学习
我有满天星辰1 小时前
第一次使用 Milvus:给我的 AI 知识库装上“记忆”
人工智能·milvus
YOLO数据集集合1 小时前
天空反无人机检测数据集 | 无人机检测 多旋翼识别 固定翼识别 低空安防 目标检测9063期
人工智能·yolo·目标检测·计算机视觉·无人机·反无人机
一木 之林1 小时前
插件、MCP、Skill 的区别?
java·c++·人工智能