faster rcnn源碼解讀(六)之minibatch

轉載自:faster rcnn源碼解讀(六)之minibatch - 野孩子的專欄 - 博客頻道 - CSDN.NET
http://blog.csdn.net/u010668907/article/details/51945917


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

minibatch源碼:https://github.com/rbgirshick/py-faster-rcnn/blob/master/lib/roi_data_layer/minibatch.py

源碼:

[python] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. # --------------------------------------------------------  
  2. # Fast R-CNN  
  3. # Copyright (c) 2015 Microsoft  
  4. # Licensed under The MIT License [see LICENSE for details]  
  5. # Written by Ross Girshick  
  6. # --------------------------------------------------------  
  7.   
  8. """Compute minibatch blobs for training a Fast R-CNN network."""  
  9.   
  10. import numpy as np  
  11. import numpy.random as npr  
  12. import cv2  
  13. from fast_rcnn.config import cfg  
  14. from utils.blob import prep_im_for_blob, im_list_to_blob  
  15.   
  16. def get_minibatch(roidb, num_classes):  
  17.     """Given a roidb, construct a minibatch sampled from it."""  
  18.     num_images = len(roidb)  
  19.     # Sample random scales to use for each image in this batch  
  20.     random_scale_inds = npr.randint(0, high=len(cfg.TRAIN.SCALES),  
  21.                                     size=num_images)#隨機索引組成的numpy,大小是roidb的長度  
  22.     assert(cfg.TRAIN.BATCH_SIZE % num_images == 0), \  
  23.         'num_images ({}) must divide BATCH_SIZE ({})'. \  
  24.         format(num_images, cfg.TRAIN.BATCH_SIZE)  
  25.     rois_per_image = cfg.TRAIN.BATCH_SIZE / num_images  
  26.     fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image)  
  27.   
  28.     # Get the input image blob, formatted for caffe  
  29.     im_blob, im_scales = _get_image_blob(roidb, random_scale_inds)  
  30.   
  31.     blobs = {'data': im_blob}  
  32.   
  33.     if cfg.TRAIN.HAS_RPN:  
  34.         assert len(im_scales) == 1"Single batch only"  
  35.         assert len(roidb) == 1"Single batch only"  
  36.         # gt boxes: (x1, y1, x2, y2, cls)  
  37.         gt_inds = np.where(roidb[0]['gt_classes'] != 0)[0]  
  38.         gt_boxes = np.empty((len(gt_inds), 5), dtype=np.float32)  
  39.         gt_boxes[:, 0:4] = roidb[0]['boxes'][gt_inds, :] * im_scales[0]  
  40.         gt_boxes[:, 4] = roidb[0]['gt_classes'][gt_inds]  
  41.         blobs['gt_boxes'] = gt_boxes  
  42.         blobs['im_info'] = np.array(  
  43.             [[im_blob.shape[2], im_blob.shape[3], im_scales[0]]],  
  44.             dtype=np.float32)  
  45.     else# not using RPN  
  46.         # Now, build the region of interest and label blobs  
  47.         rois_blob = np.zeros((05), dtype=np.float32)  
  48.         labels_blob = np.zeros((0), dtype=np.float32)  
  49.         bbox_targets_blob = np.zeros((04 * num_classes), dtype=np.float32)  
  50.         bbox_inside_blob = np.zeros(bbox_targets_blob.shape, dtype=np.float32)  
  51.         # all_overlaps = []  
  52.         for im_i in xrange(num_images):  
  53.             labels, overlaps, im_rois, bbox_targets, bbox_inside_weights \  
  54.                 = _sample_rois(roidb[im_i], fg_rois_per_image, rois_per_image,  
  55.                                num_classes)  
  56.   
  57.             # Add to RoIs blob  
  58.             rois = _project_im_rois(im_rois, im_scales[im_i])  
  59.             batch_ind = im_i * np.ones((rois.shape[0], 1))  
  60.             rois_blob_this_image = np.hstack((batch_ind, rois))  
  61.             rois_blob = np.vstack((rois_blob, rois_blob_this_image))  
  62.   
  63.             # Add to labels, bbox targets, and bbox loss blobs  
  64.             labels_blob = np.hstack((labels_blob, labels))  
  65.             bbox_targets_blob = np.vstack((bbox_targets_blob, bbox_targets))  
  66.             bbox_inside_blob = np.vstack((bbox_inside_blob, bbox_inside_weights))  
  67.             # all_overlaps = np.hstack((all_overlaps, overlaps))  
  68.   
  69.         # For debug visualizations  
  70.         # _vis_minibatch(im_blob, rois_blob, labels_blob, all_overlaps)  
  71.   
  72.         blobs['rois'] = rois_blob  
  73.         blobs['labels'] = labels_blob  
  74.   
  75.         if cfg.TRAIN.BBOX_REG:  
  76.             blobs['bbox_targets'] = bbox_targets_blob  
  77.             blobs['bbox_inside_weights'] = bbox_inside_blob  
  78.             blobs['bbox_outside_weights'] = \  
  79.                 np.array(bbox_inside_blob > 0).astype(np.float32)  
  80.   
  81.     return blobs  
  82.   
  83. def _sample_rois(roidb, fg_rois_per_image, rois_per_image, num_classes):  
  84.     """Generate a random sample of RoIs comprising foreground and background 
  85.     examples. 
  86.     """  
  87.     # label = class RoI has max overlap with  
  88.     labels = roidb['max_classes']  
  89.     overlaps = roidb['max_overlaps']  
  90.     rois = roidb['boxes']  
  91.   
  92.     # Select foreground RoIs as those with >= FG_THRESH overlap  
  93.     fg_inds = np.where(overlaps >= cfg.TRAIN.FG_THRESH)[0]  
  94.     # Guard against the case when an image has fewer than fg_rois_per_image  
  95.     # foreground RoIs  
  96.     fg_rois_per_this_image = np.minimum(fg_rois_per_image, fg_inds.size)  
  97.     # Sample foreground regions without replacement  
  98.     if fg_inds.size > 0:  
  99.         fg_inds = npr.choice(  
  100.                 fg_inds, size=fg_rois_per_this_image, replace=False)  
  101.   
  102.     # Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI)  
  103.     bg_inds = np.where((overlaps < cfg.TRAIN.BG_THRESH_HI) &  
  104.                        (overlaps >= cfg.TRAIN.BG_THRESH_LO))[0]  
  105.     # Compute number of background RoIs to take from this image (guarding  
  106.     # against there being fewer than desired)  
  107.     bg_rois_per_this_image = rois_per_image - fg_rois_per_this_image  
  108.     bg_rois_per_this_image = np.minimum(bg_rois_per_this_image,  
  109.                                         bg_inds.size)  
  110.     # Sample foreground regions without replacement  
  111.     if bg_inds.size > 0:  
  112.         bg_inds = npr.choice(  
  113.                 bg_inds, size=bg_rois_per_this_image, replace=False)  
  114.   
  115.     # The indices that we're selecting (both fg and bg)  
  116.     keep_inds = np.append(fg_inds, bg_inds)  
  117.     # Select sampled values from various arrays:  
  118.     labels = labels[keep_inds]  
  119.     # Clamp labels for the background RoIs to 0  
  120.     labels[fg_rois_per_this_image:] = 0  
  121.     overlaps = overlaps[keep_inds]  
  122.     rois = rois[keep_inds]  
  123.   
  124.     bbox_targets, bbox_inside_weights = _get_bbox_regression_labels(  
  125.             roidb['bbox_targets'][keep_inds, :], num_classes)  
  126.   
  127.     return labels, overlaps, rois, bbox_targets, bbox_inside_weights  
  128.   
  129. def _get_image_blob(roidb, scale_inds):  
  130.     """Builds an input blob from the images in the roidb at the specified 
  131.     scales. 
  132.     """  
  133.     num_images = len(roidb)  
  134.     processed_ims = []  
  135.     im_scales = []  
  136.     for i in xrange(num_images):  
  137.         im = cv2.imread(roidb[i]['image'])  
  138.         if roidb[i]['flipped']:  
  139.             im = im[:, ::-1, :]  
  140.         target_size = cfg.TRAIN.SCALES[scale_inds[i]]  
  141.         im, im_scale = prep_im_for_blob(im, cfg.PIXEL_MEANS, target_size,  
  142.                                         cfg.TRAIN.MAX_SIZE)prep_im_for_blob: util的blob.py中;用於將圖片平均後縮放。#im_scales: 每張圖片的縮放率  
[python] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1.         #  cfg.PIXEL_MEANS: 原始圖片會集體減去該值達到mean  
  2.         im_scales.append(im_scale)  
  3.         processed_ims.append(im)  
  4.   
  5.     # Create a blob to hold the input images  
  6.     blob = im_list_to_blob(processed_ims)#將以list形式存放的圖片數據處理成(batch elem, channel, height, width)的im_blob形式,height,width用的是此次計算所有圖片的最大值  
  7.   
  8.     return blob, im_scales#blob是一個字典,與name_to_top對應,方便把blob數據放進top  
  9.   
  10. def _project_im_rois(im_rois, im_scale_factor):  
  11.     """Project image RoIs into the rescaled training image."""  
  12.     rois = im_rois * im_scale_factor  
  13.     return rois  
  14.   
  15. def _get_bbox_regression_labels(bbox_target_data, num_classes):  
  16.     """Bounding-box regression targets are stored in a compact form in the 
  17.     roidb. 
  18.  
  19.     This function expands those targets into the 4-of-4*K representation used 
  20.     by the network (i.e. only one class has non-zero targets). The loss weights 
  21.     are similarly expanded. 
  22.  
  23.     Returns: 
  24.         bbox_target_data (ndarray): N x 4K blob of regression targets 
  25.         bbox_inside_weights (ndarray): N x 4K blob of loss weights 
  26.     """  
  27.     clss = bbox_target_data[:, 0]  
  28.     bbox_targets = np.zeros((clss.size, 4 * num_classes), dtype=np.float32)  
  29.     bbox_inside_weights = np.zeros(bbox_targets.shape, dtype=np.float32)  
  30.     inds = np.where(clss > 0)[0]  
  31.     for ind in inds:  
  32.         cls = clss[ind]  
  33.         start = 4 * cls  
  34.         end = start + 4  
  35.         bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]  
  36.         bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS  
  37.     return bbox_targets, bbox_inside_weights  
  38.   
  39. def _vis_minibatch(im_blob, rois_blob, labels_blob, overlaps):  
  40.     """Visualize a mini-batch for debugging."""  
  41.     import matplotlib.pyplot as plt  
  42.     for i in xrange(rois_blob.shape[0]):  
  43.         rois = rois_blob[i, :]  
  44.         im_ind = rois[0]  
  45.         roi = rois[1:]  
  46.         im = im_blob[im_ind, :, :, :].transpose((120)).copy()  
  47.         im += cfg.PIXEL_MEANS  
  48.         im = im[:, :, (210)]  
  49.         im = im.astype(np.uint8)  
  50.         cls = labels_blob[i]  
  51.         plt.imshow(im)  
  52.         print 'class: 'cls' overlap: ', overlaps[i]  
  53.         plt.gca().add_patch(  
  54.             plt.Rectangle((roi[0], roi[1]), roi[2] - roi[0],  
  55.                           roi[3] - roi[1], fill=False,  
  56.                           edgecolor='r', linewidth=3)  
  57.             )  
  58.         plt.show()  

solver.step(1)-》reshape-》forward-》_get_next_minbatch-》_get_next_minbatch_inds-》(前面在layers裏,現在進入minibatch組建真正的blob)get_minibatch

4.1 cfg.TRAIN.SCALES: 圖片被縮放的target_size列表

  4.2 random_scale_inds:列表的隨機索引組成的numpy,大小是roidb的長度

  4.3 cfg.PIXEL_MEANS: 原始圖片會集體減去該值達到mean

  4.4 im_scales: 每張圖片的縮放率

    縮放率的求法: im_scales = target_size/min(width, height);

              if im_scales*max(width, height) > cfg.TRAIN.MAX_SIZE  

                    im_scales = cfg.TRAIN.MAX_SIZE * max(width, height)

  4.5 prep_im_for_blob: utilblob.py中;用於將圖片平均後縮放。

 4.6 im_list_to_blob(ims): 將以list形式存放的圖片數據處理成(batch elem, channel, height, width)im_blob形式,heightwidth用的是此次計算所有圖片的最大值

4.7 blob是一個字典:data,一個batch的處理過的所有圖片數據,即上面的im_blob

                       im_info, [im_blob.shape[2], im_blob.shape[3], im_scales[0]]

                       gt_boxes, 是前四列是box的值,第五列是box的類別。

                              box=box*im_scales

  blobname_to_top對應,方便把blob數據放進top

!!!minibatch.py34行的代碼表明,batchsizecfg.TRAIN.IMS_PER_BATCH只能是1


發佈了85 篇原創文章 · 獲贊 519 · 訪問量 183萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章