faster rcnn源碼理解(二)之AnchorTargetLayer(網絡中的rpn_data)

轉載自:faster rcnn源碼理解(二)之AnchorTargetLayer(網絡中的rpn_data) - 野孩子的專欄 - 博客頻道 - CSDN.NET

http://blog.csdn.net/u010668907/article/details/51942481

faster用python版本的https://github.com/rbgirshick/py-faster-rcnn

AnchorTargetLayer源碼在https://github.com/rbgirshick/py-faster-rcnn/blob/master/lib/rpn/anchor_target_layer.py

源碼粘貼:

[python] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. # --------------------------------------------------------  
  2. # Faster R-CNN  
  3. # Copyright (c) 2015 Microsoft  
  4. # Licensed under The MIT License [see LICENSE for details]  
  5. # Written by Ross Girshick and Sean Bell  
  6. # --------------------------------------------------------  
  7.   
  8. import os  
  9. import caffe  
  10. import yaml  
  11. from fast_rcnn.config import cfg  
  12. import numpy as np  
  13. import numpy.random as npr  
  14. from generate_anchors import generate_anchors  
  15. from utils.cython_bbox import bbox_overlaps  
  16. from fast_rcnn.bbox_transform import bbox_transform  
  17.   
  18. DEBUG = False  
  19.   
  20. class AnchorTargetLayer(caffe.Layer):  
  21.     """ 
  22.     Assign anchors to ground-truth targets. Produces anchor classification 
  23.     labels and bounding-box regression targets. 
  24.     """  
  25.   
  26.     def setup(self, bottom, top):  
  27.         layer_params = yaml.load(self.param_str_)  
  28.         anchor_scales = layer_params.get('scales', (81632))  
  29.         self._anchors = generate_anchors(scales=np.array(anchor_scales))#九個anchor的w h x_cstr y_cstr,對原始的wh做橫向縱向變化,並放大縮小得到九個  
  30.         self._num_anchors = self._anchors.shape[0]<span style="font-family: Arial, Helvetica, sans-serif;">#anchor的個數</span>  
  31.         self._feat_stride = layer_params['feat_stride']#網絡中參數16  
  32.   
  33.         if DEBUG:  
  34.             print 'anchors:'  
  35.             print self._anchors  
  36.             print 'anchor shapes:'  
  37.             print np.hstack((  
  38.                 self._anchors[:, 2::4] - self._anchors[:, 0::4],  
  39.                 self._anchors[:, 3::4] - self._anchors[:, 1::4],  
  40.             ))  
  41.             self._counts = cfg.EPS  
  42.             self._sums = np.zeros((14))  
  43.             self._squared_sums = np.zeros((14))  
  44.             self._fg_sum = 0  
  45.             self._bg_sum = 0  
  46.             self._count = 0  
  47.   
  48.         # allow boxes to sit over the edge by a small amount  
  49.         self._allowed_border = layer_params.get('allowed_border'0)  
  50.         #bottom 長度爲4;bottom[0],map;bottom[1],boxes,labels;bottom[2],im_fo;bottom[3],圖片數據  
  51.         height, width = bottom[0].data.shape[-2:]  
  52.         if DEBUG:  
  53.             print 'AnchorTargetLayer: height', height, 'width', width  
  54.   
  55.         A = self._num_anchors#anchor的個數  
  56.         # labels  
  57.         top[0].reshape(11, A * height, width)  
  58.         # bbox_targets  
  59.         top[1].reshape(1, A * 4, height, width)  
  60.         # bbox_inside_weights  
  61.         top[2].reshape(1, A * 4, height, width)  
  62.         # bbox_outside_weights  
  63.         top[3].reshape(1, A * 4, height, width)  
  64.   
  65.     def forward(self, bottom, top):  
  66.         # Algorithm:  
  67.         #  
  68.         # for each (H, W) location i  
  69.         #   generate 9 anchor boxes centered on cell i  
  70.         #   apply predicted bbox deltas at cell i to each of the 9 anchors  
  71.         # filter out-of-image anchors  
  72.         # measure GT overlap  
  73.   
  74.         assert bottom[0].data.shape[0] == 1, \  
  75.             'Only single item batches are supported'  
  76.   
  77.         # map of shape (..., H, W)  
  78.         height, width = bottom[0].data.shape[-2:]  
  79.         # GT boxes (x1, y1, x2, y2, label)  
  80.         gt_boxes = bottom[1].data#gt_boxes:長度不定  
  81.         # im_info  
  82.         im_info = bottom[2].data[0, :]  
  83.   
  84.         if DEBUG:  
  85.             print ''  
  86.             print 'im_size: ({}, {})'.format(im_info[0], im_info[1])  
  87.             print 'scale: {}'.format(im_info[2])  
  88.             print 'height, width: ({}, {})'.format(height, width)  
  89.             print 'rpn: gt_boxes.shape', gt_boxes.shape  
  90.             print 'rpn: gt_boxes', gt_boxes  
  91.   
  92.         # 1. Generate proposals from bbox deltas and shifted anchors  
  93.         shift_x = np.arange(0, width) * self._feat_stride  
  94.         shift_y = np.arange(0, height) * self._feat_stride  
  95.         shift_x, shift_y = np.meshgrid(shift_x, shift_y)  
  96.         shifts = np.vstack((shift_x.ravel(), shift_y.ravel(),  
  97.                             shift_x.ravel(), shift_y.ravel())).transpose()  
  98.         # add A anchors (1, A, 4) to  
  99.         # cell K shifts (K, 1, 4) to get  
  100.         # shift anchors (K, A, 4)  
  101.         # reshape to (K*A, 4) shifted anchors  
  102.         A = self._num_anchors  
  103.         K = shifts.shape[0]  
  104.         all_anchors = (self._anchors.reshape((1, A, 4)) +  
  105.                        shifts.reshape((1, K, 4)).transpose((102)))  
  106.         all_anchors = all_anchors.reshape((K * A, 4))  
  107.         total_anchors = int(K * A)#K*A,所有anchors個數,包括越界的  
  108.         #K: width*height  
  109.         #A: 9  
  110.         # only keep anchors inside the image  
  111.         inds_inside = np.where(  
  112.             (all_anchors[:, 0] >= -self._allowed_border) &  
  113.             (all_anchors[:, 1] >= -self._allowed_border) &  
  114.             (all_anchors[:, 2] < im_info[1] + self._allowed_border) &  # width  
  115.             (all_anchors[:, 3] < im_info[0] + self._allowed_border)    # height  
  116.         )[0]#沒有過界的anchors索引  
  117.   
  118.         if DEBUG:  
  119.             print 'total_anchors', total_anchors  
  120.             print 'inds_inside', len(inds_inside)  
  121.   
  122.         # keep only inside anchors  
  123.         anchors = all_anchors[inds_inside, :]#沒有過界的anchors  
  124.         if DEBUG:  
  125.             print 'anchors.shape', anchors.shape  
  126.   
  127.         # label: 1 is positive, 0 is negative, -1 is dont care  
  128.         labels = np.empty((len(inds_inside), ), dtype=np.float32)  
  129.         labels.fill(-1)  
  130.   
  131.         # overlaps between the anchors and the gt boxes  
  132.         # overlaps (ex, gt)  
  133.         overlaps = bbox_overlaps(  
  134.             np.ascontiguousarray(anchors, dtype=np.float),  
  135.             np.ascontiguousarray(gt_boxes, dtype=np.float))  
  136.         argmax_overlaps = overlaps.argmax(axis=1)#overlaps每行最大值索引  
  137.         max_overlaps = overlaps[np.arange(len(inds_inside)), argmax_overlaps]  
  138.         gt_argmax_overlaps = overlaps.argmax(axis=0)  
  139.         gt_max_overlaps = overlaps[gt_argmax_overlaps,  
  140.                                    np.arange(overlaps.shape[1])]  
  141.         gt_argmax_overlaps = np.where(overlaps == gt_max_overlaps)[0]  
  142.   
  143.         if not cfg.TRAIN.RPN_CLOBBER_POSITIVES:  
  144.             # assign bg labels first so that positive labels can clobber them  
  145.             labels[max_overlaps < cfg.TRAIN.RPN_NEGATIVE_OVERLAP] = 0  
  146.   
  147.         # fg label: for each gt, anchor with highest overlap  
  148.         labels[gt_argmax_overlaps] = 1  
  149.   
  150.         # fg label: above threshold IOU  
  151.         labels[max_overlaps >= cfg.TRAIN.RPN_POSITIVE_OVERLAP] = 1  
  152.   
  153.         if cfg.TRAIN.RPN_CLOBBER_POSITIVES:  
  154.             # assign bg labels last so that negative labels can clobber positives  
  155.             labels[max_overlaps < cfg.TRAIN.RPN_NEGATIVE_OVERLAP] = 0  
  156.   
  157.         # subsample positive labels if we have too many  
  158.         num_fg = int(cfg.TRAIN.RPN_FG_FRACTION * cfg.TRAIN.RPN_BATCHSIZE)  
  159.         fg_inds = np.where(labels == 1)[0]  
  160.         if len(fg_inds) > num_fg:  
  161.             disable_inds = npr.choice(  
  162.                 fg_inds, size=(len(fg_inds) - num_fg), replace=False)  
  163.             labels[disable_inds] = -1  
  164.   
  165.         # subsample negative labels if we have too many  
  166.         num_bg = cfg.TRAIN.RPN_BATCHSIZE - np.sum(labels == 1)  
  167.         bg_inds = np.where(labels == 0)[0]  
  168.         if len(bg_inds) > num_bg:  
  169.             disable_inds = npr.choice(  
  170.                 bg_inds, size=(len(bg_inds) - num_bg), replace=False)  
  171.             labels[disable_inds] = -1  
  172.             #print "was %s inds, disabling %s, now %s inds" % (  
  173.                 #len(bg_inds), len(disable_inds), np.sum(labels == 0))  
  174.   
  175.         bbox_targets = np.zeros((len(inds_inside), 4), dtype=np.float32)  
  176.         bbox_targets = _compute_targets(anchors, gt_boxes[argmax_overlaps, :])  
  177.   
  178.         bbox_inside_weights = np.zeros((len(inds_inside), 4), dtype=np.float32)  
  179.         bbox_inside_weights[labels == 1, :] = np.array(cfg.TRAIN.RPN_BBOX_INSIDE_WEIGHTS)  
  180.   
  181.         bbox_outside_weights = np.zeros((len(inds_inside), 4), dtype=np.float32)  
  182.         if cfg.TRAIN.RPN_POSITIVE_WEIGHT < 0:  
  183.             # uniform weighting of examples (given non-uniform sampling)  
  184.             num_examples = np.sum(labels >= 0)  
  185.             positive_weights = np.ones((14)) * 1.0 / num_examples  
  186.             negative_weights = np.ones((14)) * 1.0 / num_examples  
  187.         else:  
  188.             assert ((cfg.TRAIN.RPN_POSITIVE_WEIGHT > 0) &  
  189.                     (cfg.TRAIN.RPN_POSITIVE_WEIGHT < 1))  
  190.             positive_weights = (cfg.TRAIN.RPN_POSITIVE_WEIGHT /  
  191.                                 np.sum(labels == 1))  
  192.             negative_weights = ((1.0 - cfg.TRAIN.RPN_POSITIVE_WEIGHT) /  
  193.                                 np.sum(labels == 0))  
  194.         bbox_outside_weights[labels == 1, :] = positive_weights  
  195.         bbox_outside_weights[labels == 0, :] = negative_weights  
  196.   
  197.         if DEBUG:  
  198.             self._sums += bbox_targets[labels == 1, :].sum(axis=0)  
  199.             self._squared_sums += (bbox_targets[labels == 1, :] ** 2).sum(axis=0)  
  200.             self._counts += np.sum(labels == 1)  
  201.             means = self._sums / self._counts  
  202.             stds = np.sqrt(self._squared_sums / self._counts - means ** 2)  
  203.             print 'means:'  
  204.             print means  
  205.             print 'stdevs:'  
  206.             print stds  
  207.   
  208.         # map up to original set of anchors  
  209.         labels = _unmap(labels, total_anchors, inds_inside, fill=-1)  
  210.         bbox_targets = _unmap(bbox_targets, total_anchors, inds_inside, fill=0)  
  211.         bbox_inside_weights = _unmap(bbox_inside_weights, total_anchors, inds_inside, fill=0)  
  212.         bbox_outside_weights = _unmap(bbox_outside_weights, total_anchors, inds_inside, fill=0)  
  213.   
  214.         if DEBUG:  
  215.             print 'rpn: max max_overlap', np.max(max_overlaps)  
  216.             print 'rpn: num_positive', np.sum(labels == 1)  
  217.             print 'rpn: num_negative', np.sum(labels == 0)  
  218.             self._fg_sum += np.sum(labels == 1)  
  219.             self._bg_sum += np.sum(labels == 0)  
  220.             self._count += 1  
  221.             print 'rpn: num_positive avg'self._fg_sum / self._count  
  222.             print 'rpn: num_negative avg'self._bg_sum / self._count  
  223.   
  224.         # labels  
  225.         labels = labels.reshape((1, height, width, A)).transpose(0312)  
  226.         labels = labels.reshape((11, A * height, width))  
  227.         top[0].reshape(*labels.shape)  
  228.         top[0].data[...] = labels  
  229.   
  230.         # bbox_targets  
  231.         bbox_targets = bbox_targets \  
  232.             .reshape((1, height, width, A * 4)).transpose(0312)  
  233.         top[1].reshape(*bbox_targets.shape)  
  234.         top[1].data[...] = bbox_targets  
  235.   
  236.         # bbox_inside_weights  
  237.         bbox_inside_weights = bbox_inside_weights \  
  238.             .reshape((1, height, width, A * 4)).transpose(0312)  
  239.         assert bbox_inside_weights.shape[2] == height  
  240.         assert bbox_inside_weights.shape[3] == width  
  241.         top[2].reshape(*bbox_inside_weights.shape)  
  242.         top[2].data[...] = bbox_inside_weights  
  243.   
  244.         # bbox_outside_weights  
  245.         bbox_outside_weights = bbox_outside_weights \  
  246.             .reshape((1, height, width, A * 4)).transpose(0312)  
  247.         assert bbox_outside_weights.shape[2] == height  
  248.         assert bbox_outside_weights.shape[3] == width  
  249.         top[3].reshape(*bbox_outside_weights.shape)  
  250.         top[3].data[...] = bbox_outside_weights  
  251.   
  252.     def backward(self, top, propagate_down, bottom):  
  253.         """This layer does not propagate gradients."""  
  254.         pass  
  255.   
  256.     def reshape(self, bottom, top):  
  257.         """Reshaping happens during the call to forward."""  
  258.         pass  
  259.   
  260.   
  261. def _unmap(data, count, inds, fill=0):  
  262.     """ Unmap a subset of item (data) back to the original set of items (of 
  263.     size count) """  
  264.     if len(data.shape) == 1:  
  265.         ret = np.empty((count, ), dtype=np.float32)  
  266.         ret.fill(fill)  
  267.         ret[inds] = data  
  268.     else:  
  269.         ret = np.empty((count, ) + data.shape[1:], dtype=np.float32)  
  270.         ret.fill(fill)  
  271.         ret[inds, :] = data  
  272.     return ret  
  273.   
  274.   
  275. def _compute_targets(ex_rois, gt_rois):  
  276.     """Compute bounding-box regression targets for an image."""  
  277.   
  278.     assert ex_rois.shape[0] == gt_rois.shape[0]  
  279.     assert ex_rois.shape[1] == 4  
  280.     assert gt_rois.shape[1] == 5  
  281.   
  282.     return bbox_transform(ex_rois, gt_rois[:, :4]).astype(np.float32, copy=False)  
總結筆記:
rpn-data是AnchorTargetLayer
bottom 長度爲4;bottom[0],map;bottom[1],boxes,labels;bottom[2],im_fo;bottom[3],圖片數據
self._feat_stride:網絡中參數16
self._anchors:九個anchor的w h x_cstr y_cstr,對原始的wh做橫向縱向變化,並放大縮小得到九個
self._num_anchors:anchor的個數


inds_inside:沒有過界的anchors索引
anchors:沒有過界的anchors
argmax_overlaps:overlaps每行最大值索引
total_anchors: K*A,所有anchors個數,包括越界的
K: width*height
A: 9


gt_boxes:長度不定


bbox_overlaps: 返回:
overlaps: (len(inds_inside)* len(gt_boxes))


論文筆記:我們分配正標籤給兩類anchor:(i)與某個ground truth(GT)包圍盒有最高的IoU(Intersection-over-Union,交集並集之比)重疊的anchor(也許不到0.7),(ii)與任意GT包圍盒有大於0.7的IoU交疊的anchor。
labels:0,bg; 1,fg; -1, on care,(len(inds_inside));over_laps列最大值對應行座標=1; over_laps行最大值 > 0.7,行=1; over_laps行最大值 < 0.3,行=0
正樣本數量由他們控制:cfg.TRAIN.RPN_FG_FRACTION * cfg.TRAIN.RPN_BATCHSIZE(128),小於等於
負樣本數量。。。。。:cfg.TRAIN.RPN_BATCHSIZE - np.sum(labels == 1)
cfg.TRAIN.RPN_BATCHSIZE:  256,最終輸出proposal數量控制


多的proposal被隨機搞成-1了。。。。。。隨機


bbox_inside_weights: label等於1的行,它的值等於cfg.TRAIN.RPN_BBOX_INSIDE_WEIGHTS(1.0);其他等於0;(len(inds_inside), 4);相當於損失函數中的pi*


cfg.TRAIN.RPN_POSITIVE_WEIGHT:  -1.0


bbox_outside_weights:fg,bg=np.ones((1, 4)) * 1.0 / sum(fg+bg),其他爲0;(len(inds_inside), 4)


_unmap: 建立一個total_anchors*第一個參數列的數組;全用fill填充;再把inds_inside對應的行用第一個參數對應的行填充 
發佈了85 篇原創文章 · 獲贊 519 · 訪問量 183萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章