anchor box 生成

本文详细解析了Faster R-CNN中锚框(Anchor)的生成过程,包括如何通过基锚框生成不同比例和尺度的锚框,以及如何在特征图上滑动产生所有锚框。附带Python代码示例。

代码如下:调用 generate_anchors()函数

# --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick and Sean Bell
# --------------------------------------------------------

import numpy as np

# Verify that we compute the same anchors as Shaoqing's matlab implementation:
#
#    >> load output/rpn_cachedir/faster_rcnn_VOC2007_ZF_stage1_rpn/anchors.mat
#    >> anchors
#
#    anchors =
#
#       -83   -39   100    56
#      -175   -87   192   104
#      -359  -183   376   200
#       -55   -55    72    72
#      -119  -119   136   136
#      -247  -247   264   264
#       -35   -79    52    96
#       -79  -167    96   184
#      -167  -343   184   360

#array([[ -83.,  -39.,  100.,   56.],
#       [-175.,  -87.,  192.,  104.],
#       [-359., -183.,  376.,  200.],
#       [ -55.,  -55.,   72.,   72.],
#       [-119., -119.,  136.,  136.],
#       [-247., -247.,  264.,  264.],
#       [ -35.,  -79.,   52.,   96.],
#       [ -79., -167.,   96.,  184.],
#       [-167., -343.,  184.,  360.]])

def generate_anchors(base_size=16, ratios=[0.5, 1, 2],
                     scales=2**np.arange(3, 6)):
    """
    Generate anchor (reference) windows by enumerating aspect ratios X
    scales wrt a reference (0, 0, 15, 15) window.
    """
    base_anchor = np.array([1, 1, base_size, base_size]) - 1 
    ratio_anchors = _ratio_enum(base_anchor, ratios)
    anchors = np.vstack([_scale_enum(ratio_anchors[i, :], scales)
                         for i in xrange(ratio_anchors.shape[0])])
    return anchors

def _whctrs(anchor):
    """
    Return width, height, x center, and y center for an anchor (window).
    """

    w = anchor[2] - anchor[0] + 1
    h = anchor[3] - anchor[1] + 1
    x_ctr = anchor[0] + 0.5 * (w - 1)
    y_ctr = anchor[1] + 0.5 * (h - 1)
    return w, h, x_ctr, y_ctr

def _mkanchors(ws, hs, x_ctr, y_ctr):
    """
    Given a vector of widths (ws) and heights (hs) around a center
    (x_ctr, y_ctr), output a set of anchors (windows).
    """

    ws = ws[:, np.newaxis]
    hs = hs[:, np.newaxis]
    anchors = np.hstack((x_ctr - 0.5 * (ws - 1),
                         y_ctr - 0.5 * (hs - 1),
                         x_ctr + 0.5 * (ws - 1),
                         y_ctr + 0.5 * (hs - 1)))
    return anchors

def _ratio_enum(anchor, ratios):
    """
    Enumerate a set of anchors for each aspect ratio wrt an anchor.
    """

    w, h, x_ctr, y_ctr = _whctrs(anchor)
    size = w * h
    size_ratios = size / ratios
    ws = np.round(np.sqrt(size_ratios))
    hs = np.round(ws * ratios)
    anchors = _mkanchors(ws, hs, x_ctr, y_ctr)
    return anchors

def _scale_enum(anchor, scales):
    """
    Enumerate a set of anchors for each scale wrt an anchor.
    """

    w, h, x_ctr, y_ctr = _whctrs(anchor)
    ws = w * scales
    hs = h * scales
    anchors = _mkanchors(ws, hs, x_ctr, y_ctr)
    return anchors

1.首先根据base anchor 生成对应得宽高比anchor

2.根据宽高比anchor, 通过scale 大小对应base anchor生成不同尺寸得 anchor

3.通过featuremap与原始图(训练时大小)的映射滑动产生所有anchor

https://blog.youkuaiyun.com/sinat_33486980/article/details/81099093

https://blog.youkuaiyun.com/jmu201521121021/article/details/87877721

### Anchor Box 的原理与应用 #### 1. **Anchor Box 的基本概念** Anchor Box 是一种用于目标检测的方法,在深度学习领域中广泛应用。它的核心思想是在图像的不同位置预先设定一系列固定大小和比例的边界框(bounding boxes),称为 anchor boxes 或 anchors[^1]。这些预定义的框覆盖整个输入图像,作为潜在的目标区域。 #### 2. **Anchor Box生成机制** 在 Faster R-CNN 中,Anchor Box 被引入以替代传统的 Selective Search 和 Edge Boxes 方法。具体来说,每个特征图上的像素点都会对应多个 anchor boxes,它们具有不同的尺度(scale)和宽高比(aspect ratio)。例如,对于某个特定的特征点,可能会有三种尺寸(小、中、大)和两种宽高比(正方形、矩形),总共生成六个 anchor boxes[^3]。 这些 anchor boxes 映射回原始图像后,能够覆盖各种形状和大小的对象。通过卷积神经网络(CNN),模型会预测每个 anchor 是否包含对象及其类别概率,并调整其坐标以更好地匹配真实目标的位置。 #### 3. **Anchor Box 的优化过程** 为了提高效率并减少冗余计算,Faster R-CNN 使用 Region Proposal Network (RPN) 自动生成候选框。相比于传统方法需要处理约 2000 个候选框,这种方法显著降低了时间复杂度[^3]。此外,由于 anchor boxes 是由 CNN 动态生成而非手工设计,因此更加灵活且适应性强。 #### 4. **无锚框算法对比** 尽管 Anchor-Based 方法取得了巨大成功,但也存在局限性,比如超参数设置困难以及对极端纵横比物体表现不佳等问题。为此,研究者提出了 KeyPoint-Based 方法,如 CornerNet,它不依赖于任何预设的 bounding box 模板,而是直接寻找目标的关键点(通常是左上角和右下角顶点)来构建最终检测框[^2]。这种方式不仅简化了流程还提升了精度特别是针对细长型物品的情况。 #### 5. **实际应用场景** - **自动驾驶**: 准确识别道路上行人车辆等移动障碍物至关重要; - **安防监控**: 实现全天候实时视频流分析预警功能; - **医疗影像诊断辅助工具开发** : 自动标记病变区域帮助医生快速定位病灶; 以上均需借助高效精准的目标探测技术才能达成预期效果,而anchor box正是满足这一需求的重要组成部分之一. ```python import torch from torchvision.models.detection import fasterrcnn_resnet50_fpn model = fasterrcnn_resnet50_fpn(pretrained=True) device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') model.to(device) def predict(image_tensor): model.eval() with torch.no_grad(): predictions = model([image_tensor.to(device)]) return predictions ``` 此代码片段展示了如何加载预训练好的 Faster R-CNN 模型并将数据送入 GPU 进行推理运算的过程。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值