这段代码包括由输入图片随机生成相应的RoIs,并生成相应的blobs,由roidb得到相应的

minibatch。其代码如下。

  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 #每张图的rois
  26. fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image) #目标rois
  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: #每个blobs包含图片中相应的box、gt_box信息
  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((0, 5), dtype=np.float32)
  48. labels_blob = np.zeros((0), dtype=np.float32)
  49. bbox_targets_blob = np.zeros((0, 4 * 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. #随机生成前景和背景的RoIs
  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. #由相应尺度的roidb生成相应的blob
  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 utilblob.py中;用于将图片平均后缩放。#im_scales 每张图片的缩放率
  143. # cfg.PIXEL_MEANS: 原始图片会集体减去该值达到mean
  144. im_scales.append(im_scale)
  145. processed_ims.append(im)
  146.  
  147. # Create a blob to hold the input images
  148. blob = im_list_to_blob(processed_ims)#将以list形式存放的图片数据处理成(batch elem, channel, height, width)的im_blob形式,heightwidth用的是此次计算所有图片的最大值
  149.  
  150. return blob, im_scales#blob是一个字典,与name_to_top对应,方便把blob数据放进top
  151.  
  152. def _project_im_rois(im_rois, im_scale_factor): #图片缩放时,相应的rois也进行缩放
  153. """Project image RoIs into the rescaled training image."""
  154. rois = im_rois * im_scale_factor
  155. return rois
  156. #由roidb返回相应的box及inside_weights
  157. def _get_bbox_regression_labels(bbox_target_data, num_classes):
  158. """Bounding-box regression targets are stored in a compact form in the
  159. roidb.
  160.  
  161. This function expands those targets into the 4-of-4*K representation used
  162. by the network (i.e. only one class has non-zero targets). The loss weights
  163. are similarly expanded.
  164.  
  165. Returns:
  166. bbox_target_data (ndarray): N x 4K blob of regression targets
  167. bbox_inside_weights (ndarray): N x 4K blob of loss weights
  168. """
  169. clss = bbox_target_data[:, 0]
  170. bbox_targets = np.zeros((clss.size, 4 * num_classes), dtype=np.float32)
  171. bbox_inside_weights = np.zeros(bbox_targets.shape, dtype=np.float32)
  172. inds = np.where(clss > 0)[0]
  173. for ind in inds:
  174. cls = clss[ind]
  175. start = 4 * cls
  176. end = start + 4
  177. bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]
  178. bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS
  179. return bbox_targets, bbox_inside_weights
  180.  
  181. def _vis_minibatch(im_blob, rois_blob, labels_blob, overlaps):
  182. """Visualize a mini-batch for debugging."""
  183. import matplotlib.pyplot as plt
  184. for i in xrange(rois_blob.shape[0]):
  185. rois = rois_blob[i, :]
  186. im_ind = rois[0]
  187. roi = rois[1:]
  188. im = im_blob[im_ind, :, :, :].transpose((1, 2, 0)).copy()
  189. im += cfg.PIXEL_MEANS
  190. im = im[:, :, (2, 1, 0)]
  191. im = im.astype(np.uint8)
  192. cls = labels_blob[i]
  193. plt.imshow(im)
  194. print 'class: ', cls, ' overlap: ', overlaps[i]
  195. plt.gca().add_patch(
  196. plt.Rectangle((roi[0], roi[1]), roi[2] - roi[0],
  197. roi[3] - roi[1], fill=False,
  198. edgecolor='r', linewidth=3)
  199. )
  200. plt.show()

r-cnn学习(八):minibatch的更多相关文章

  1. Python Tutorial 学习(八)--Errors and Exceptions

    Python Tutorial 学习(八)--Errors and Exceptions恢复 Errors and Exceptions 错误与异常 此前,我们还没有开始着眼于错误信息.不过如果你是一 ...

  2. CNN学习笔记:批标准化

    CNN学习笔记:批标准化 Batch Normalization Batch Normalization, 批标准化, 是将分散的数据统一的一种做法, 也是优化神经网络的一种方法. 在神经网络的训练过 ...

  3. R基础学习

    R基础学习 The Art of R Programming 1.seq 产生等差数列:seq(from,to,by) seq(from,to,length) for(i in 1:length(x) ...

  4. 卷积神经网络(CNN)学习笔记1:基础入门

    卷积神经网络(CNN)学习笔记1:基础入门 Posted on 2016-03-01   |   In Machine Learning  |   9 Comments  |   14935  Vie ...

  5. SVG 学习<八> SVG的路径——path(2)贝塞尔曲线命令、光滑贝塞尔曲线命令

    目录 SVG 学习<一>基础图形及线段 SVG 学习<二>进阶 SVG世界,视野,视窗 stroke属性 svg分组 SVG 学习<三>渐变 SVG 学习<四 ...

  6. R语言学习 第四篇:函数和流程控制

    变量用于临时存储数据,而函数用于操作数据,实现代码的重复使用.在R中,函数只是另一种数据类型的变量,可以被分配,操作,甚至把函数作为参数传递给其他函数.分支控制和循环控制,和通用编程语言的风格很相似, ...

  7. CNN学习笔记:目标函数

    CNN学习笔记:目标函数 分类任务中的目标函数 目标函数,亦称损失函数或代价函数,是整个网络模型的指挥棒,通过样本的预测结果与真实标记产生的误差来反向传播指导网络参数学习和表示学习. 假设某分类任务共 ...

  8. CNN学习笔记:卷积神经网络

    CNN学习笔记:卷积神经网络 卷积神经网络 基本结构 卷积神经网络是一种层次模型,其输入是原始数据,如RGB图像.音频等.卷积神经网络通过卷积(convolution)操作.汇合(pooling)操作 ...

  9. CNN学习笔记:全连接层

    CNN学习笔记:全连接层 全连接层 全连接层在整个网络卷积神经网络中起到“分类器”的作用.如果说卷积层.池化层和激活函数等操作是将原始数据映射到隐层特征空间的话,全连接层则起到将学到的特征表示映射到样 ...

  10. CNN学习笔记:池化层

    CNN学习笔记:池化层 池化 池化(Pooling)是卷积神经网络中另一个重要的概念,它实际上是一种形式的降采样.有多种不同形式的非线性池化函数,而其中“最大池化(Max pooling)”是最为常见 ...

随机推荐

  1. 【C#】【Thread】SpinWait

    System.Threading.SpinWait 是一个轻量同步类型,可以在低级别方案中使用它来避免内核事件所需的高开销的上下文切换和内核转换. 在多核计算机上,当预计资源不会保留很长一段时间时,如 ...

  2. Error:Execution failed for task ':app:transformClassesWithDexForDebug'解决记录

    转载请标明出处: http://blog.csdn.net/lxk_1993/article/details/50511172 本文出自:[lxk_1993的博客]:   3个错误non-zero e ...

  3. npm设置prefix 路径

    Windows下的Nodejs npm路径是appdata,很不爽,想改回来,但是在cmd下执行以下命令也无效 npm config set cache "D:\nodejs\node_ca ...

  4. mysql重置密码

    1.首先停止正在运行的MySQL进程 复制代码代码如下: >net stop mysql  如未加载为服务,可直接在进程管理器或者服务中进行关闭. 2.以安全模式启动MySQL 进入mysql目 ...

  5. Netron源码解读(一):GraphControl画布对象

    GraphControl是Netron中比较重要的一个类,属于所有图形作图的画布.它管理着画布上的所有图形对象的移动.变形.连接.拖放.这些功能很重要的一部分是通过对鼠标事件的处理实现的.下面我们就看 ...

  6. JS获取回车事件(兼容各浏览器)

    一.用到onkeydown获取事件动作, 二.用到键盘对应代码keyCode, 三. var event=arguments.callee.caller.arguments[0]||window.ev ...

  7. 【Python】[面向对象高级编程] 使用__slots__,使用@property

    1.使用 __slots__    给实例绑定方法, >>> def set_age(self, age): # 定义一个函数作为实例方法 ... self.age = age .. ...

  8. 软件工程(FZU2015)赛季得分榜,第七回合

    目录 第一回合 第二回合 第三回合 第四回合 第五回合 第6回合 第7回合 第8回合 第9回合 第10回合 第11回合 积分规则 积分制: 作业为10分制,练习为3分制:alpha30分: 团队项目分 ...

  9. 如何完全卸载(Mac&Windows)office 365 ProPlus

    Q: 如何完全卸载office 365 ProPlus,如果用户使用之前的office版本没有卸载干净(配置文件中保持了原有的Key)会造成新安装的office 365 ProPlus 或者最新版的o ...

  10. 正确遍历ElasticSearch索引

    1:ElasticSearch的查询过程 2:由ES查询模式引起的深度分页问题 3:如何正确遍历索引中的数据 ElasticSearch的查询过程 es的数据查询分两步: 第一步是的结果是获取满足查询 ...