在上文《 faster-rcnn系列学习之准备数据》,我们已经介绍了imdb与roidb的一些情况,下面我们准备再继续说一下rpn阶段和fast rcnn阶段的数据准备整个处理流程。
由于这两个阶段的数据准备有些重合,所以放在一起说明。
我们并行地从train_rpn与train_fast_rcnn说起,这两个函数在train_faster_rcnn_alt_opt.py中。
def train_rpn(queue=None, imdb_name=None, init_model=None, solver=None,
max_iters=None, cfg=None):
"""Train a Region Proposal Network in a separate training process.
"""
# Not using any proposals, just ground-truth boxes
cfg.TRAIN.HAS_RPN = True
cfg.TRAIN.BBOX_REG = False # applies only to Fast R-CNN bbox regression
cfg.TRAIN.PROPOSAL_METHOD = 'gt'
cfg.TRAIN.IMS_PER_BATCH = 1
print 'Init model: {}'.format(init_model)
print('Using config:')
pprint.pprint(cfg)
import caffe
_init_caffe(cfg)
roidb, imdb = get_roidb(imdb_name)
print 'roidb len: {}'.format(len(roidb))
output_dir = get_output_dir(imdb)
print 'Output will be saved to `{:s}`'.format(output_dir)
model_paths = train_net(solver, roidb, output_dir,
pretrained_model=init_model,
max_iters=max_iters)
# Cleanup all but the final model
for i in model_paths[:-1]:
os.remove(i)
rpn_model_path = model_paths[-1]
# Send final model path through the multiprocessing queue
queue.put({'model_path': rpn_model_path})
def train_fast_rcnn(queue=None, imdb_name=None, init_model=None, solver=None,
max_iters=None, cfg=None, rpn_file=None):
"""Train a Fast R-CNN using proposals generated by an RPN.
"""
cfg.TRAIN.HAS_RPN = False # not generating prosals on-the-fly
cfg.TRAIN.PROPOSAL_METHOD = 'rpn' # use pre-computed RPN proposals instead
cfg.TRAIN.IMS_PER_BATCH = 2
print 'Init model: {}'.format(init_model)
print 'RPN proposals: {}'.format(rpn_file)
print('Using config:')
pprint.pprint(cfg)
import caffe
_init_caffe(cfg)
roidb, imdb = get_roidb(imdb_name, rpn_file=rpn_file)
output_dir = get_output_dir(imdb)
print 'Output will be saved to `{:s}`'.format(output_dir)
# Train Fast R-CNN
model_paths = train_net(solver, roidb, output_dir,
pretrained_model=init_model,
max_iters=max_iters)
# Cleanup all but the final model
for i in model_paths[:-1]:
os.remove(i)
fast_rcnn_model_path = model_paths[-1]
# Send Fast R-CNN model path over the multiprocessing queue
queue.put({'model_path': fast_rcnn_model_path})
显然两段代码很相似。很显然,两个子网络都从vgg-16开始训起,自然初始输入是相似的。
但设置不同,rpn:
cfg.TRAIN.HAS_RPN = True
cfg.TRAIN.PROPOSAL_METHOD = 'gt' #使用gt_roidb
cfg.TRAIN.IMS_PER_BATCH = 1
而fast rcnn;
cfg.TRAIN.HAS_RPN = False
cfg.TRAIN.PROPOSAL_METHOD = 'rpn' #使用rpn_roidb
cfg.TRAIN.IMS_PER_BATCH = 2
我们接下来从roidb, imdb = get_roidb(imdb_name)说起。
def get_roidb(imdb_name, rpn_file=None):
imdb = get_imdb(imdb_name)#通过工厂类获取图片数据库信息
print 'Loaded dataset `{:s}` for training'.format(imdb.name)
imdb.set_proposal_method(cfg.TRAIN.PROPOSAL_METHOD)
print 'Set proposal method: {:s}'.format(cfg.TRAIN.PROPOSAL_METHOD)
if rpn_file is not None:
imdb.config['rpn_file'] = rpn_file
roidb = get_training_roidb(imdb)#获得训练数据
return roidb, imdb
我们先看这句:
def set_proposal_method(self, method):
method = eval('self.' + method + '_roidb') # python中eval是可以具体运行里面的字符串的
self.roidb_handler = method
对于rpn来说: eval('self.gt_roidb');
对于fast rcnn来说:eval('self.rpn_roidb');eval是python的语法,指运行里面的字符串。这里这两个命令都在pascal_voc.py中。我们逐一来看。
rpn:
def gt_roidb(self):
"""
Return the database of ground-truth regions of interest.
This function loads/saves from/to a cache file to speed up future calls.
"""
cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl')
if os.path.exists(cache_file):
with open(cache_file, 'rb') as fid:
roidb = cPickle.load(fid)
print '{} gt roidb loaded from {}'.format(self.name, cache_file)
return roidb
gt_roidb = [self._load_pascal_annotation(index)
for index in self.image_index]
with open(cache_file, 'wb') as fid:
cPickle.dump(gt_roidb, fid, cPickle.HIGHEST_PROTOCOL)
print 'wrote gt roidb to {}'.format(cache_file)
return gt_roidb
这个函数是pascal_voc对象的核心函数之一,它将返回roidb数据对象。
def _load_pascal_annotation(self, index):
"""
Load image and bounding boxes info from XML file in the PASCAL VOC
format.
"""
filename = os.path.join(self._data_path, 'Annotations', index + '.xml')
tree = ET.parse(filename)
objs = tree.findall('object')
if not self.config['use_diff']:
# Exclude the samples labeled as difficult
non_diff_objs = [
obj for obj in objs if int(obj.find('difficult').text) == 0]
# if len(non_diff_objs) != len(objs):
# print 'Removed {} difficult objects'.format(
# len(objs) - len(non_diff_objs))
objs = non_diff_objs
num_objs = len(objs)
boxes = np.zeros((num_objs, 4), dtype=np.uint16)
gt_classes = np.zeros((num_objs), dtype=np.int32)
overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32)
# "Seg" area for pascal is just the box area
seg_areas = np.zeros((num_objs), dtype=np.float32)
# Load object bounding boxes into a data frame.
for ix, obj in enumerate(objs):
bbox = obj.find('bndbox')
# Make pixel indexes 0-based
x1 = float(bbox.find('xmin').text) - 1
y1 = float(bbox.find('ymin').text) - 1
x2 = float(bbox.find('xmax').text) - 1
y2 = float(bbox.find('ymax').text) - 1
cls = self._class_to_ind[obj.find('name').text.lower().strip()]
boxes[ix, :] = [x1, y1, x2, y2]
gt_classes[ix] = cls
overlaps[ix, cls] = 1.0
seg_areas[ix] = (x2 - x1 + 1) * (y2 - y1 + 1)
overlaps = scipy.sparse.csr_matrix(overlaps)
return {'boxes' : boxes,
'gt_classes': gt_classes,
'gt_overlaps' : overlaps,
'flipped' : False,
'seg_areas' : seg_areas}
该函数根据每个图像的索引,到Annotations这个文件夹下去找相应的xml标注数据,然后加载所有的bounding box对象,并去除所有的“复杂”对象。
def rpn_roidb(self):
if int(self._year) == 2007 or self._image_set != 'test':
gt_roidb = self.gt_roidb()
rpn_roidb = self._load_rpn_roidb(gt_roidb)
roidb = imdb.merge_roidbs(gt_roidb, rpn_roidb)
else:
roidb = self._load_rpn_roidb(None)
return roidb
def _load_rpn_roidb(self, gt_roidb):
filename = self.config['rpn_file']
print 'loading {}'.format(filename)
assert os.path.exists(filename), \
'rpn data not found at: {}'.format(filename)
with open(filename, 'rb') as f:
box_list = cPickle.load(f)
return self.create_roidb_from_box_list(box_list, gt_roidb)
在经过RPN网络产生了proposal以后,这个函数作用是将这些proposal 的 roi与groudtruth结合起来,变成rpn_roidb.
def create_roidb_from_box_list(self, box_list, gt_roidb):
assert len(box_list) == self.num_images, \
'Number of boxes must match number of ground-truth images' # box_list是一个数组,每个元素是一个列表,每个列表指一幅图像中含有的盒子个数
roidb = []
for i in xrange(self.num_images):
boxes = box_list[i]
num_boxes = boxes.shape[0] # 行为盒子序号,列为盒子坐标
overlaps = np.zeros((num_boxes, self.num_classes), dtype=np.float32)
if gt_roidb is not None and gt_roidb[i]['boxes'].size > 0:
gt_boxes = gt_roidb[i]['boxes']
gt_classes = gt_roidb[i]['gt_classes']
gt_overlaps = bbox_overlaps(boxes.astype(np.float),
gt_boxes.astype(np.float))
argmaxes = gt_overlaps.argmax(axis=1)
maxes = gt_overlaps.max(axis=1)
I = np.where(maxes > 0)[0]
overlaps[I, gt_classes[argmaxes[I]]] = maxes[I]
overlaps = scipy.sparse.csr_matrix(overlaps)
roidb.append({
'boxes' : boxes,
'gt_classes' : np.zeros((num_boxes,), dtype=np.int32), #为0
'gt_overlaps' : overlaps,
'flipped' : False,
'seg_areas' : np.zeros((num_boxes,), dtype=np.float32),
})
return roidb
box_list是一个数组,每个元素是一个列表,每个列表指一幅图像中含有的盒子 。gt_roidb自然是rpn训练阶段获得的ground truth 盒子的情况。
bbox_overlaps:每个proposal的box都与groud-truth的box做一次重合度计算,与anchor _target _layer.py中类似
overlap = (重合部分面积) / (proposal _box面积 + gt_boxes面积 - 重合部分面积)
对于每个proposal,选出最大的那个gt _boxes的值所对应的类别,然后填写相应地重叠值,到相应的class index下。
这里fast rcnn生成的roidb,结构与rpn的相同。而gt_overlaps如下:
0 (背景类) 1 2 。。。。 21
1 0 0.8 0 0
2 0 0 0.6 0
3 0 0 0 0 (全0,为背景)
; ..............................................
n 0 0 0 0.8
横坐标是盒子的序号,纵坐标是种类。这里需要知道的是对于每一个盒子,我们记录它的重叠度,考虑是与某一种类的重叠度,而没有记录下与某个ground truth box的重叠度。有可能出现这样的情况,某个图片含有两个猫,而一个候选框与这两只猫的ground truth box的重叠度相同,且最大。那么我们没有必要记住与哪个猫重叠度最大,而只需要知道是与猫重叠度最大。因为这里重叠度仅仅是用来与阈值做比较的。排除掉某些低前景的box. 后面进行box的回归也会出现类似的情况。待后续。
#将一般是两个roidb堆叠在一起,进行合并。
@staticmethod
def merge_roidbs(a, b):
assert len(a) == len(b)
for i in xrange(len(a)):
a[i]['boxes'] = np.vstack((a[i]['boxes'], b[i]['boxes'])) # 竖着堆叠
a[i]['gt_classes'] = np.hstack((a[i]['gt_classes'], # 横着拉长
b[i]['gt_classes']))
a[i]['gt_overlaps'] = scipy.sparse.vstack([a[i]['gt_overlaps'],b[i]['gt_overlaps']]) #竖着堆叠
a[i]['seg_areas'] = np.hstack((a[i]['seg_areas'],
b[i]['seg_areas']))
return a
最后fast rcnn在训练阶段返回的是含有ground truth box与proposal box的roidb的信息,在测试时仅返回proposal box的roidb的信息。
这里参与计算的一定是所有rpn阶段提取的proposals.
get_roidb 中还有最后一步:get_training_roidb。参考http://blog.csdn.net/xiamentingtao/article/details/78449751 ,
对于生成的roidb新增了一些属性。形成了如下信息:
接下来我们再看train_net,他们在train.py中。该程序封装了一个Solver,并且定义了snapshot.并且这里生成了box对应的回归目标。下面我们仔细分析。
def train_net(solver_prototxt, roidb, output_dir,
pretrained_model=None, max_iters=40000):
"""Train a Fast R-CNN network.""" # 其实还有rpn
roidb = filter_roidb(roidb)
sw = SolverWrapper(solver_prototxt, roidb, output_dir,
pretrained_model=pretrained_model)
print 'Solving...'
model_paths = sw.train_model(max_iters)
print 'done solving'
return model_paths
首先过滤掉一些box。
def filter_roidb(roidb):
"""Remove roidb entries that have no usable RoIs."""
def is_valid(entry): # entry是指一幅图片
# Valid images have:
# (1) At least one foreground RoI OR
# (2) At least one background RoI
overlaps = entry['max_overlaps']
# find boxes with sufficient overlap
fg_inds = np.where(overlaps >= cfg.TRAIN.FG_THRESH)[0] #返回所有满足条件的序号列表
# Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI)
bg_inds = np.where((overlaps < cfg.TRAIN.BG_THRESH_HI) &
(overlaps >= cfg.TRAIN.BG_THRESH_LO))[0]
# image is only valid if such boxes exist
valid = len(fg_inds) > 0 or len(bg_inds) > 0
return valid
num = len(roidb)
filtered_roidb = [entry for entry in roidb if is_valid(entry)]
num_after = len(filtered_roidb)
print 'Filtered {} roidb entries: {} -> {}'.format(num - num_after,
num, num_after)
return filtered_roidb
该函数中定义了一个is_valid函数,用于判断roidb中的每个entry(图片)是否合理,合 理定义为至少有一个前景box或背景box。
class SolverWrapper(object):
"""A simple wrapper around Caffe's solver.
This wrapper gives us control over he snapshotting process, which we
use to unnormalize the learned bounding-box regression weights.
"""
def __init__(self, solver_prototxt, roidb, output_dir,
pretrained_model=None):
"""Initialize the SolverWrapper."""
self.output_dir = output_dir
if (cfg.TRAIN.HAS_RPN and cfg.TRAIN.BBOX_REG and
cfg.TRAIN.BBOX_NORMALIZE_TARGETS):
# RPN can only use precomputed normalization because there are no
# fixed statistics to compute a priori
assert cfg.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED
# 计算box回归目标,并且返回各类的偏移均值和方差,
if cfg.TRAIN.BBOX_REG:
print 'Computing bounding-box regression targets...'
self.bbox_means, self.bbox_stds = \
rdl_roidb.add_bbox_regression_targets(roidb)
print 'done'
self.solver = caffe.SGDSolver(solver_prototxt)
# 预训练参数写入
if pretrained_model is not None:
print ('Loading pretrained model '
'weights from {:s}').format(pretrained_model)
self.solver.net.copy_from(pretrained_model)
self.solver_param = caffe_pb2.SolverParameter()
with open(solver_prototxt, 'rt') as f:
pb2.text_format.Merge(f.read(), self.solver_param)
#所有的前面的数据准备工作都是为了这一句话,将roidb设置进去,接下来就正式进入剖析训练过程的部分了。
self.solver.net.layers[0].set_roidb(roidb)
首先对于rpn来说,cfg.TRAIN.BBOX_REG=false,因此不需要计算各类的偏移均值和方差。这是必然的,
因为rpn刚开始是没有anchor的,只有图片和groundtruth box,自然就不需要计算回归目标了,而在fast rcnn阶段才需要。所以
如下的操作是针对在rpn提取proposal形成的roidb操作的。而且根据config.py的
设置:
__C.TRAIN.BBOX_NORMALIZE_TARGETS = True
# Deprecated (inside weights)
__C.TRAIN.BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0)
# Normalize the targets using "precomputed" (or made up) means and stdevs
# (BBOX_NORMALIZE_TARGETS must also be True)
__C.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED = False
__C.TRAIN.BBOX_NORMALIZE_MEANS = (0.0, 0.0, 0.0, 0.0)
__C.TRAIN.BBOX_NORMALIZE_STDS = (0.1, 0.1, 0.2, 0.2)
(啰嗦一点,不知道清楚没?)
def add_bbox_regression_targets(roidb):
"""Add information needed to train bounding-box regressors."""
assert len(roidb) > 0
assert 'max_classes' in roidb[0], 'Did you call prepare_roidb first?'
num_images = len(roidb)#这里的个数是rpn提取的所有proposal的个数
# Infer number of classes from the number of columns in gt_overlaps
num_classes = roidb[0]['gt_overlaps'].shape[1]
for im_i in xrange(num_images):
rois = roidb[im_i]['boxes']
max_overlaps = roidb[im_i]['max_overlaps']
max_classes = roidb[im_i]['max_classes']
roidb[im_i]['bbox_targets'] = \
_compute_targets(rois, max_overlaps, max_classes)
if cfg.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED:
# Use fixed / precomputed "means" and "stds" instead of empirical values
means = np.tile(
np.array(cfg.TRAIN.BBOX_NORMALIZE_MEANS), (num_classes, 1))
stds = np.tile(
np.array(cfg.TRAIN.BBOX_NORMALIZE_STDS), (num_classes, 1))
else:
# Compute values needed for means and stds
# var(x) = E(x^2) - E(x)^2
class_counts = np.zeros((num_classes, 1)) + cfg.EPS
sums = np.zeros((num_classes, 4))
squared_sums = np.zeros((num_classes, 4))
for im_i in xrange(num_images):
targets = roidb[im_i]['bbox_targets']
for cls in xrange(1, num_classes):
cls_inds = np.where(targets[:, 0] == cls)[0]
if cls_inds.size > 0:
class_counts[cls] += cls_inds.size
sums[cls, :] += targets[cls_inds, 1:].sum(axis=0)
squared_sums[cls, :] += \
(targets[cls_inds, 1:] ** 2).sum(axis=0)
means = sums / class_counts
stds = np.sqrt(squared_sums / class_counts - means ** 2)
print 'bbox target means:'
print means
print means[1:, :].mean(axis=0) # ignore bg class
print 'bbox target stdevs:'
print stds
print stds[1:, :].mean(axis=0) # ignore bg class
# Normalize targets
if cfg.TRAIN.BBOX_NORMALIZE_TARGETS:
print "Normalizing targets"
for im_i in xrange(num_images):
targets = roidb[im_i]['bbox_targets']
for cls in xrange(1, num_classes):
cls_inds = np.where(targets[:, 0] == cls)[0]
roidb[im_i]['bbox_targets'][cls_inds, 1:] -= means[cls, :]
roidb[im_i]['bbox_targets'][cls_inds, 1:] /= stds[cls, :]
else:
print "NOT normalizing targets"
# These values will be needed for making predictions
# (the predicts will need to be unnormalized and uncentered)
return means.ravel(), stds.ravel()# 返回的是铺平后的向量,也就是由21*4变成了1*(21*4)=1*84
这个函数首先计算了bbox_targets,为roidb增加了一个key:bbox_targets,主要通过函数_compute_targets来实现。而后面则利用rpn阶段提取的所有box的bbox_targets分别计算了各类的偏移均值和方差,shape是num_classes*4,(由于参与计算均值和方差的box显然个数很多,所以大部分的类均应该都可以计算出均值和方差,唯独强调的是这里的box也有可能是
背景,但是我们这里不计算背景类,所以means,和stds的第一行为(0,0,0,0)。
然后使用计算出的均值和方差对bbox_targets进行了归一化。最后返回铺平后的均值和方差。shape也就是由21*4变成了1*(21*4)=1*84
下面我们来看_compute_targets。
这个函数用来计算一张图片的所有box的回归信息。这将直接应用于在后面的回归损失计算。
def _compute_targets(rois, overlaps, labels): # 参数rois只含有当前图片的box信息
"""Compute bounding-box regression targets for an image."""
# Indices目录 of ground-truth ROIs
# ground-truth ROIs
gt_inds = np.where(overlaps == 1)[0]
if len(gt_inds) == 0:
# Bail if the image has no ground-truth ROIs
# 不存在gt ROI,返回空数组
return np.zeros((rois.shape[0], 5), dtype=np.float32)
# Indices of examples for which we try to make predictions
# BBOX阈值,只有ROI与gt的重叠度大于阈值,这样的ROI才能用作bb回归的训练样本
ex_inds = np.where(overlaps >= cfg.TRAIN.BBOX_THRESH)[0]
# Get IoU overlap between each ex ROI and gt ROI
# 计算ex ROI and gt ROI的IoU
ex_gt_overlaps = bbox_overlaps(
# 变数据格式为float
np.ascontiguousarray(rois[ex_inds, :], dtype=np.float),
np.ascontiguousarray(rois[gt_inds, :], dtype=np.float))
# Find which gt ROI each ex ROI has max overlap with:
# this will be the ex ROI's gt target
# 这里每一行代表一个ex_roi,列代表gt_roi,元素数值代表两者的IoU
gt_assignment = ex_gt_overlaps.argmax(axis=1) #按行求最大,返回索引.
gt_rois = rois[gt_inds[gt_assignment], :] #每个ex_roi对应的gt_rois,与下面ex_roi数量相同
ex_rois = rois[ex_inds, :]
targets = np.zeros((rois.shape[0], 5), dtype=np.float32)
targets[ex_inds, 0] = labels[ex_inds] #第一个元素是label
targets[ex_inds, 1:] = bbox_transform(ex_rois, gt_rois) #后4个元素是ex_box与gt_box的4个方位的偏移
return targets
根据前面,在fast rcnn中准备roidb时,已经包含了rpn阶段提取的proposal与ground truth box.而groundtruth roidb的overlaps=1,所以我们可以轻松找到所有的ground truth box.
整个过程怎么找每个box对应的ground truth box呢?实际上就是重新计算了每个box对ground truth box的重合度,然后
寻找重合度最大的对应ground truth.,进而计算偏差,输出的是一个二维数组,横坐标是盒子的序号,纵坐标是5维,第一维是类别,第二维到第五维为偏移。
而且这里实际上所有的ground truth也都参与了与groundtruth box的重合度计算,自然自己与自己的重叠度最大,后面计算回归量时,他们的回归量正好都为0.因此整个
target非0的均是proposal的回归目标。
【注意:】这里参与计算target的是那些最大重叠度>阈值(0.5)的前景proposal.但是整个targets返回的shape却是n*5,其中n为rois的盒子个数,包括了所有的proposal与groundtruth box。没有计算的,target为0.
计算偏移可以参考文档:http://caffecn.cn/?/question/160 王斌_ICT 的pdf文件
这样得到的fast rcnn的roidb的情况如下:
roidb[img_index]包含的key, | value |
boxes | box位置信息,box_num*4的np array (x1,y1,x2,y2) |
gt_overlaps | 所有box在不同类别的得分,box_num*class_num矩阵 |
gt_classes | 所有box的真实类别,box_num长度的list |
flipped | 是否翻转 |
image | 该图片的路径,字符串 |
width | 图片的宽 |
height | 图片的高 |
max_overlaps | 每个box的在所有类别的得分最大值,box_num长度 |
max_classes | 每个box的得分最高所对应的类,box_num长度 |
bbox_targets | 每个box的类别,以及与最接近的gt-box的4个方位偏移 (共5列)(c,tx,ty,tw,th) |
接下来预训练的imagenet的参数写入,并且将准备好的roidb送入网络的第一层。 调用layer.py中的set_roidb方法,为网络的第一层(RoIDataLayer)设置roidb同时打乱顺序
这样做是必然的,毕竟类imdb或者pascal_voc的实例中的roidb必须要传到layer中,网络才能继续向前传播;
在RoIDataLayer的foward方法中,就是将RoIDataLayer实例的_roidb拷贝给RoIDataLayer的top blob。
最后我们再来看一下数据准备的最后一步,也就是layer.py的RoIDataLayer类。 明确这里我们向网络层输入的roidb是所有的图片的roidb,且看它如何批处理。
对于rpn,网络的第一层为:
layer {
name: 'input-data'
type: 'Python'
top: 'data'
top: 'im_info'
top: 'gt_boxes'
python_param {
module: 'roi_data_layer.layer'
layer: 'RoIDataLayer'
param_str: "'num_classes': 21"
}
}
对于fast rcnn,网络的第一层为:
layer {
name: 'data'
type: 'Python'
top: 'data'
top: 'rois'
top: 'labels'
top: 'bbox_targets'
top: 'bbox_inside_weights'
top: 'bbox_outside_weights'
python_param {
module: 'roi_data_layer.layer'
layer: 'RoIDataLayer'
param_str: "'num_classes': 21"
}
}
首先看set_roidb。
def set_roidb(self, roidb):
"""Set the roidb to be used by this layer during training."""
self._roidb = roidb
self._shuffle_roidb_inds()
if cfg.TRAIN.USE_PREFETCH:
self._blob_queue = Queue(10)
self._prefetch_process = BlobFetcher(self._blob_queue,
self._roidb,
self._num_classes)
self._prefetch_process.start()
# Terminate the child process when the parent exists
def cleanup():
print 'Terminating BlobFetcher'
self._prefetch_process.terminate()
self._prefetch_process.join()
import atexit
atexit.register(cleanup)
我们接下来重要的是看setup,它将设置批次处理的规模。
def setup(self, bottom, top):
"""Setup the RoIDataLayer."""
# parse the layer parameter string, which must be valid YAML
layer_params = yaml.load(self.param_str_)
self._num_classes = layer_params['num_classes']
self._name_to_top_map = {}
# data blob: holds a batch of N images, each with 3 channels
idx = 0
top[idx].reshape(cfg.TRAIN.IMS_PER_BATCH, 3, # 对于rpn,data的规模为1*3*600*1000 ,对于fast rcnn,2*3*600*1000
max(cfg.TRAIN.SCALES), cfg.TRAIN.MAX_SIZE)
self._name_to_top_map['data'] = idx
idx += 1
if cfg.TRAIN.HAS_RPN: # 对于rpn设置
top[idx].reshape(1, 3)
self._name_to_top_map['im_info'] = idx # 设置im_info每行的规模是1*3,后面可以看到为(h,w,scale)
idx += 1
top[idx].reshape(1, 4)
self._name_to_top_map['gt_boxes'] = idx #设置gt_boxes每行的规模是1*4
idx += 1
else: # not using RPN #对于fast rcnn设置
# rois blob: holds R regions of interest, each is a 5-tuple
# (n, x1, y1, x2, y2) specifying an image batch index n and a
# rectangle (x1, y1, x2, y2)
top[idx].reshape(1, 5) # 设置rois每行的规模是1*5,(n, x1, y1, x2, y2) ,n是图片的序号,后面是矩形的坐标
self._name_to_top_map['rois'] = idx
idx += 1
# labels blob: R categorical labels in [0, ..., K] for K foreground
# classes plus background
top[idx].reshape(1)
self._name_to_top_map['labels'] = idx #设置labels每行的规模是1,分别取自[0, ..., K],0为背景,其他是前景
idx += 1
if cfg.TRAIN.BBOX_REG: # 同样对于fast rcnn,默认设为true
# bbox_targets blob: R bounding-box regression targets with 4
# targets per class
top[idx].reshape(1, self._num_classes * 4) #设置bbox_targets每行的规模是1*(_num_classes * 4),也即是1*84
self._name_to_top_map['bbox_targets'] = idx
idx += 1
# bbox_inside_weights blob: At most 4 targets per roi are active;
# thisbinary vector sepcifies the subset of active targets
top[idx].reshape(1, self._num_classes * 4)
self._name_to_top_map['bbox_inside_weights'] = idx #设置bbox_inside_weights每行的规模是1*(_num_classes * 4),也即是1*84
idx += 1
top[idx].reshape(1, self._num_classes * 4) #bbox_outside_weights每行的规模是1*(_num_classes * 4),也即是1*84
self._name_to_top_map['bbox_outside_weights'] = idx
idx += 1
print 'RoiDataLayer: name_to_top:', self._name_to_top_map
assert len(top) == len(self._name_to_top_map)
下面我们来看forward,这才开始真正的数据传递。其实我们这时候发现其实在roidb中并没有存储图片的像素值,而只有到了这一步才开始正式读取图片的像素值。
def forward(self, bottom, top):
"""Get blobs and copy them into this layer's top blob vector."""
blobs = self._get_next_minibatch()
for blob_name, blob in blobs.iteritems():
top_ind = self._name_to_top_map[blob_name]
# Reshape net's input blobs
top[top_ind].reshape(*(blob.shape))
# Copy data into net's input blobs
top[top_ind].data[...] = blob.astype(np.float32, copy=False)
def _get_next_minibatch(self):
"""Return the blobs to be used for the next minibatch.
If cfg.TRAIN.USE_PREFETCH is True, then blobs will be computed in a
separate process and made available through self._blob_queue.
"""
if cfg.TRAIN.USE_PREFETCH:
return self._blob_queue.get()
else:
db_inds = self._get_next_minibatch_inds() #这里包含了一个批次的图片个数
minibatch_db = [self._roidb[i] for i in db_inds]
return get_minibatch(minibatch_db, self._num_classes)
下面我们看一下这个函数:
def _get_next_minibatch_inds(self):
"""Return the roidb indices for the next minibatch."""
if self._cur + cfg.TRAIN.IMS_PER_BATCH >= len(self._roidb):
self._shuffle_roidb_inds()
db_inds = self._perm[self._cur:self._cur + cfg.TRAIN.IMS_PER_BATCH]
self._cur += cfg.TRAIN.IMS_PER_BATCH
return db_inds
当训练多次,所有的图片都训练完了,将会打乱所有的图片的排序,重新提取序号。这里一个roidb就是代表一张图片。所以有时候会将二者不加区别。
这时一个批次的数据序号准备好了,就可以读取像素值了。且看get_minibatch。这时我们跳到《Faster RCNN minibatch.py解读》
总的来说,对于一个minibatch的训练样本来说,这里的所有top都存储了一批量roi的信息(指的是__C.TRAIN.BATCH_SIZE = 128),其中前景与背景box的比为1:3,对于某些符合要求的前景box进行了相应地计算,尤其是回归目标,选出的前景图像除ground truth box以外都是有的,背景类显然没有(也就是全为0)。存储的blob的各key的规模可以参考setup.
最后参与运算的都在bbox_targets ,bbox_inside_weights ,bbox_outside_weights中体现出来(即非0项)。
接下来就是数据的拷贝。至此数据的准备工作结束。数据流的第一层输入完毕。
这里有一个小小的疑问:
1. 在setup中,gt_boxes的规模为1*4,而在_get_next_minibatch返回的blobs中,gt_boxes为1*5,(x1,y1,x2,y2,c).有点矛盾啊?