最详细的Faster-RCNN代码解读Pytorch版 (一) generate_anchors.py

简介  

 

Faster-RCNN是在之前提出的Fast-RCNN上进行的改进,由于之前的两步目标检测模型大多都是采用Selective Search进行Proposals的生成,这个操作是需要在CPU上进行计算的,所以会导致耗费特别长的计算时间,论文中指出,在测试过程中,生成一张图像的proposals大概耗时1.5s左右,严重影响了整个检测过程的时间,所以这篇文章主要提出了RPN网络,将生成待选框的操作也交给了深度学习,这样有了GPU加速的优势,生成待选框的时间基本上可以忽略不计。

 

模型概览

 

在这里插入图片描述

模型主要分为以上的几个部分,绿色是模型的主要模块。

  • 左侧Dataset就是需要训练的数据集,其中COCO和VOC都是比较经典的目标检测数据集。
  • 上方RPN就是论文中新提出的生成待选框的模块,任务就是生成proposals
  • 中间的VGG是提取图像特征的部分,VGG是论文提出时最好的图像分类模型,现在已经有ResNet等作为替代。
  • 最右边的ROI Pooling。ROI的意思就是Region of Interest,指的是在特征图中那些待选区域的映射,随后要进行pooing以进行后面的操作。

我找的代码是Pytorch版本的(由于原版需要的框架都比较老,有大神在Pytorch上实现了1.0版本)

以下是Pytorch1.0版本的代码链接:faster-rcnn.pytorch

下面就逐个模块的理解一下代码,就从第一步RPN开始:

(一)RPN部分

简介

RPN主要完成的任务是在图像中利用神经网络去寻找待选区域(Proposals),模型主要接收卷积层提供的feature map,然后分别包含了两个全连接层,一个是box-regression layer,另一个是box-classification layer。前者是边框回归,主要是看生成的待选框和真实的bounding box有多大的差距,进行回归,第二个是分类模型,他就是一个简单的softmax二分类的操作,主要任务是区分这个区域是一个目标对象还是背景。NMS是对proposals进行了一个筛选,避免了冗余和浪费,接下来让我们看一下RPN网络整体的操作:

  • 模型输入:卷积层的feature map以及ground truth的BBox
  • 模型输出:感兴趣的区域ROIs
  • 模型构造:一个Classification一个Regression
  • 损失函数

 

接下来开始进入代码部分:

generate_anchors主要用于生成anchor,anchor是根据feature map中特征点,来生成边框,这个边框是不准的,所以要经历回归这步,来和ground_truth进行回归,在fasterRCNN总共生成了3个不同的纵横比radio=[0.5, 1, 2]以及三种尺度scale=[8, 16, 32].

from __future__ import print_function
# --------------------------------------------------------
# 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
import pdb

# 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.]])

try:
    xrange          # Python 2
except NameError:
    xrange = range  # Python 3  
# 这个的上面是python2和python3的兼容
#=====================================
# 函数输入:给定基本anchor的大小16,以及一系列ratio和scales
# 函数输出:根据一个base anchor和三个横纵比和大小,生成9个不同的anchor
#=====================================
# 这是整个代码里面最核心的一个函数,建议先看下面的函数再来看这个
# 首先输入了一个base_size是16,三种尺度0.5,1,2以及三种scales分别是2的3,4,5次方8,16,32
# 先生成了一个基本的anchor[0, 0, 15, 15]
# 然后通过这个anchor来迭代不同的ratio,这样就生成了3个anchor
# 最后再用这三个anchors迭代不同的scales最后生成了9个anchors
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


#=====================================
#_whctrs(anchor)
#函数输入:一个anchor的左下角右上角坐标
#函数输出:一个anchor的w,h, 以及中心点坐标(x_ctr, y_ctr)
#=====================================
# 这个函数是返回一个anchor的width, height, 中心点坐标(x, y)
# 其中anchor是一个数组,0,1,2,3分别表示的anchor的左上角,右下角坐标(X1, y1) (x2, y2)
# 经过计算就能得到w和h,以及中心点x_ctr和y_ctr
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

#===================================
# 函数输入:一组宽和一组高,以及中心点
# 函数输出:其中一组是四个值,分别是这个anchor的左下角右上角的坐标
#===================================
# 给定一组对于中心点(x_ctr, y_ctr)的w和h的向量,生成一系列的anchors
# np.newaxis相当于增加一维,比如ws.shape是(3,)经过处理后变成(3, 1)
# 之所以要对长度和宽度进行-1是因为长度宽度里面同样保存着中心点,所以要减1
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

#==========================================
# 函数输入:一个scale相同的anchor,以及一系列横纵比
# 函数输出:这个相同scale不同ratio的anchors左下角右上角的坐标们
#==========================================
# 这是一个迭代器,主要迭代每一个anchor的长宽比
# 使用_whctrs这个函数计算出一个anchor的宽,高以及中心点坐标
# size计算了面积,比如w=8, h=4 size=32
# 如果radio是[0.5, 1, 2] size_ratios=64, 32, 16
# np.round是四舍五入的函数
# 设宽是x那么高就是radio*x,面积是radio*x^2,所以size/radio就是w的平方,于是就可以求出w和h
# 这里面对于一种scale的anchor只是横纵比不同,面积是相同的
# 然后再通过_mkanchors计算出这一系列anchor的左下角右上角坐标
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

#=============================================
# 函数输入:一个anchor以及scales的大小
# 函数输入:经过这一系列scale输出的一系列anchor的左下角右上角坐标
#=============================================
# 这个就和上面的一样,上面是对ratio进行迭代,这个是对scales进行迭代
# 和上面一样,先计算w,h,中心点x, y
# 比如scale是[8, 16, 32]
# w h如果是4,那么返回的wh就是32,64, 128,这样就根据中心点生成了这三种scale

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

# 这里是整个文件的主函数
# 计算了一下生成9个anchor所需要的时间
# 然后打印了一下生成的9个标准框的左下角右上角的坐标

if __name__ == '__main__':
    import time
    t = time.time()
    a = generate_anchors()
    print(time.time() - t)
    print(a)
    from IPython import embed; embed()

 

运行结果如下:

总结一下,这一个代码主要是根据一个base_anchor[0, 0, 15, 15]来生成9个ratio为[0.5, 1, 2] scale为[8, 16, 32]标准anchors

  • 6
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值