faster rcnn RPN之anchor(generate_anchors)源码解析

英文原文:faste rcnn。其中生成RPN(Regional proposal network)的python代码解析

本代码主要用于:生成尺度为:128,256,512; 宽高比为:1:2,1:1,2:1的anchor

<span style="font-size:24px;">#功能描述:生成多尺度、多宽高比的anchors。
#          尺度为:128,256,512; 宽高比为:1:2,1:1,2:1

import numpy as np  #提供矩阵运算功能的库

#生成anchors总函数:ratios为一个列表,表示宽高比为:1:2,1:1,2:1
#2**x表示:2^x,scales:[2^3 2^4 2^5],即:[8 16 32]
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  #新建一个数组:base_anchor:[0 0 15 15]
    ratio_anchors = _ratio_enum(base_anchor, ratios)  #枚举各种宽高比
    anchors = np.vstack([_scale_enum(ratio_anchors[i, :], scales)  #枚举各种尺度,vstack:竖向合并数组
                         for i in xrange(ratio_anchors.shape[0])]) #shape[0]:读取矩阵第一维长度,其值为3
    return anchors

#用于返回width,height,(x,y)中心坐标(对于一个anchor窗口)
def _whctrs(anchor):
    """
    Return width, height, x center, and y center for an anchor (window).
    """
	#anchor:存储了窗口左上角,右下角的坐标
    w = anchor[2] - anchor[0] + 1
    h = anchor[3] - anchor[1] + 1
    x_ctr = anchor[0] + 0.5 * (w - 1)  #anchor中心点坐标
    y_ctr = anchor[1] + 0.5 * (h - 1)
    return w, h, x_ctr, y_ctr

#给定一组宽高向量,输出各个anchor,即预测窗口,**输出anchor的面积相等,只是宽高比不同**
def _mkanchors(ws, hs, x_ctr, y_ctr):
    #ws:[23 16 11],hs:[12 16 22],ws和hs一一对应。
    """
    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]  #newaxis:将数组转置
    hs = hs[:, np.newaxis]
    anchors = np.hstack((x_ctr - 0.5 * (ws - 1),    #hstack、vstack:合并数组
                         y_ctr - 0.5 * (hs - 1),    #anchor:[[-3.5 2 18.5 13]
                         x_ctr + 0.5 * (ws - 1),     #        [0  0  15  15]
                         y_ctr + 0.5 * (hs - 1)))     #       [2.5 -3 12.5 18]]
    return anchors

#枚举一个anchor的各种宽高比,anchor[0 0 15 15],ratios[0.5,1,2]
def _ratio_enum(anchor, ratios):
    """   列举关于一个anchor的三种宽高比 1:2,1:1,2:1
    Enumerate a set of anchors for each aspect ratio wrt an anchor.
    """

    w, h, x_ctr, y_ctr = _whctrs(anchor)  #返回宽高和中心坐标,w:16,h:16,x_ctr:7.5,y_ctr:7.5
    size = w * h   #size:16*16=256
    size_ratios = size / ratios  #256/ratios[0.5,1,2]=[512,256,128]
    #round()方法返回x的四舍五入的数字,sqrt()方法返回数字x的平方根
    ws = np.round(np.sqrt(size_ratios)) #ws:[23 16 11]
    hs = np.round(ws * ratios)    #hs:[12 16 22],ws和hs一一对应。as:23&12
    anchors = _mkanchors(ws, hs, x_ctr, y_ctr)  #给定一组宽高向量,输出各个预测窗口
    return anchors

#枚举一个anchor的各种尺度,以anchor[0 0 15 15]为例,scales[8 16 32]
def _scale_enum(anchor, scales):
    """   列举关于一个anchor的三种尺度 128*128,256*256,512*512
    Enumerate a set of anchors for each scale wrt an anchor.
    """
    w, h, x_ctr, y_ctr = _whctrs(anchor) #返回宽高和中心坐标,w:16,h:16,x_ctr:7.5,y_ctr:7.5
    ws = w * scales   #[128 256 512]
    hs = h * scales   #[128 256 512]
    anchors = _mkanchors(ws, hs, x_ctr, y_ctr) #[[-56 -56 71 71] [-120 -120 135 135] [-248 -248 263 263]]
    return anchors

if __name__ == '__main__':  #主函数
    import time
    t = time.time()
    a = generate_anchors()  #生成anchor(窗口)
    print time.time() - t   #显示时间
    print a
    from IPython import embed; embed()
</span>

       其中,_ratio_enum()部分生成三种宽高比 1:2,1:1,2:1的anchor如下图所示:
       其中,_scale_enum()部分,生成三种尺寸的anchor,以_ratio_enum()部分生成的anchor[0 0 15 15]为例,扩展了三种尺度 128*128,256*256,512*512,如下图所示:

### Faster R-CNN 工作原理详解 #### 1. 区域提议网络 (RPN) Faster R-CNN 中最重要的改进在于引入了区域提议网络(Region Proposal Network, RPN),取代了传统的选择性搜索方法来生成候选框。RPN 是一种全卷积网络,能够高效地生成高质量的候选框[^1]。 ```python class RegionProposalNetwork(nn.Module): def forward(self, feature_map): # 使用滑动窗口在特征图上生成锚点 anchors = generate_anchors(feature_map) # 对每个锚点预测其是否为物体以及调整边框位置 objectness_scores, bbox_deltas = predict_objectness_and_bbox(anchors) return objectness_scores, bbox_deltas ``` #### 2. 候选框生成与筛选 RPN 输出大量候选框后,会对其进行非极大值抑制处理,去除重叠度较高的候选框,并保留最有可能包含目标的对象建议框。这些经过筛选后的候选框会被传递给后续模块进行分类和回归操作。 #### 3. ROI Pooling 层 为了使不同大小的候选框具有相同的尺寸输入到全连接层中,Faster R-CNN 设计了一个特殊的池化层——ROI Pooling 层。该层可以根据不同的候选框自适应地提取固定大小的空间特征向量[^2]。 ```python def roi_pooling(input_features, rois, pooled_height=7, pooled_width=7): output = [] for roi in rois: # 计算感兴趣区域对应的特征图上的坐标范围 start_h, end_h, start_w, end_w = calculate_roi_coordinates(roi) # 自适应最大池化得到固定维度表示 pooled_feature = adaptive_max_pool( input_features[start_h:end_h, start_w:end_w], (pooled_height, pooled_width)) output.append(pooled_feature.flatten()) return torch.stack(output) ``` #### 4. 分类与边界框回归 最后一步是对每一个候选框执行二分类任务(背景 vs 物体类别)并优化边界框的位置参数。这部分采用了 Fast R-CNN 的设计思路,在共享卷积层基础上添加两个平行支路分别负责分类和定位任务。 ```python class RCNNHead(nn.Module): def __init__(self, num_classes): super().__init__() self.fc_layers = nn.Sequential( nn.Linear(in_features=pooled_size * pooled_size * conv_channels, out_features=fc_hidden_units), nn.ReLU(), ... ) self.classifier = nn.Linear(fc_hidden_units, num_classes + 1) # 加1是因为有背景类 self.bbox_regressor = nn.Linear(fc_hidden_units, 4 * num_classes) def forward(self, pooled_rois): features = self.fc_layers(pooled_rois) class_logits = self.classifier(features) bbox_preds = self.bbox_regressor(features) return class_logits, bbox_preds ```
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值