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

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

相关推荐
红衣小蛇妖19 分钟前
神经网络-Day45
人工智能·深度学习·神经网络
JoannaJuanCV35 分钟前
BEV和OCC学习-5:数据预处理流程
深度学习·目标检测·3d·occ·bev
KKKlucifer35 分钟前
当AI遇上防火墙:新一代智能安全解决方案全景解析
人工智能
DisonTangor1 小时前
【小红书拥抱开源】小红书开源大规模混合专家模型——dots.llm1
人工智能·计算机视觉·开源·aigc
浠寒AI3 小时前
智能体模式篇(上)- 深入 ReAct:LangGraph构建能自主思考与行动的 AI
人工智能·python
weixin_505154463 小时前
数字孪生在建设智慧城市中可以起到哪些作用或帮助?
大数据·人工智能·智慧城市·数字孪生·数据可视化
Best_Me073 小时前
深度学习模块缝合
人工智能·深度学习
YuTaoShao4 小时前
【论文阅读】YOLOv8在单目下视多车目标检测中的应用
人工智能·yolo·目标检测
算家计算4 小时前
字节开源代码模型——Seed-Coder 本地部署教程,模型自驱动数据筛选,让每行代码都精准落位!
人工智能·开源
伪_装4 小时前
大语言模型(LLM)面试问题集
人工智能·语言模型·自然语言处理