faster-rcnn 之 基于roidb get_minibatch(数据准备操作)

【说明】:欢迎加入:faster-rcnn 交流群 238138700这个函数,输入是roidb,根据roidb中给出的图片的信息,读取图片的源文件,然后整理成blobs,供给网络训练使用;

def get_minibatch(roidb, num_classes):

这个函数会根据roidb中的信息,调用opencv读取图片,整理成blobs返回,所以这个函数是faster-rcnn实际的数据准备操作,我们来分析minibatch.py这个文件;

【输入】:roidb是一个list,list中的每个元素是一个字典,每个字典对应一张图片的信息,其中的主要信息有:

boxes:该图片所有的box的4个坐标位置

gt_class:每个boxes对应的类别

gt_overlaps

height:图片原始的高

width:图片原始的宽

image:图片的路径

seg_areas

【函数解析】:

def get_minibatch(roidb, num_classes):
    """Given a roidb, construct a minibatch sampled from it."""
    num_images = len(roidb)#roidb中元素的个数,就是要处理的图片的个数
    # Sample random scales to use for each image in this batch
    random_scale_inds = npr.randint(0, high=len(cfg.TRAIN.SCALES),
                                    size=num_images)#根据scales的数量,为每张图片生成一个scales的索引
    assert(cfg.TRAIN.BATCH_SIZE % num_images == 0), \
        'num_images ({}) must divide BATCH_SIZE ({})'. \
        format(num_images, cfg.TRAIN.BATCH_SIZE)#断言,要求batchsize必须是图片数量的整数倍
    rois_per_image = cfg.TRAIN.BATCH_SIZE / num_images #计算平均从每个图片上要产生多少个roi输入
    fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image) #按比率计算每张图片的roi中需要多少个前景

    # Get the input image blob, formatted for caffe
    im_blob, im_scales = _get_image_blob(roidb, random_scale_inds)#调用函数,读取图片数据,返回矩阵数据和每张图片的尺寸缩放信息

    blobs = {'data': im_blob}#把blobs字典的key:data赋值为im_blob,也就是图片的矩阵数据

    if cfg.TRAIN.HAS_RPN:#这里是针对RPN网络的训练过程的
        assert len(im_scales) == 1, "Single batch only"
        assert len(roidb) == 1, "Single batch only"
        # gt boxes: (x1, y1, x2, y2, cls)#gt_boxes每一行对应一个box信息,包括4个坐标和一个类别
        gt_inds = np.where(roidb[0]['gt_classes'] != 0)[0]
        gt_boxes = np.empty((len(gt_inds), 5), dtype=np.float32)
        gt_boxes[:, 0:4] = roidb[0]['boxes'][gt_inds, :] * im_scales[0]
        gt_boxes[:, 4] = roidb[0]['gt_classes'][gt_inds]
        blobs['gt_boxes'] = gt_boxes
        blobs['im_info'] = np.array(
            [[im_blob.shape[2], im_blob.shape[3], im_scales[0]]],
            dtype=np.float32)#图像信息就是rezise后的高、宽、缩放比例三个信息
    else: # not using RPN
        # Now, build the region of interest and label blobs
        rois_blob = np.zeros((0, 5), dtype=np.float32)
        labels_blob = np.zeros((0), dtype=np.float32)
        bbox_targets_blob = np.zeros((0, 4 * num_classes), dtype=np.float32)
        bbox_inside_blob = np.zeros(bbox_targets_blob.shape, dtype=np.float32)
        # all_overlaps = []
        for im_i in xrange(num_images):
            labels, overlaps, im_rois, bbox_targets, bbox_inside_weights \
                = _sample_rois(roidb[im_i], fg_rois_per_image, rois_per_image,
                               num_classes)

            # Add to RoIs blob
            rois = _project_im_rois(im_rois, im_scales[im_i])
            batch_ind = im_i * np.ones((rois.shape[0], 1))
            rois_blob_this_image = np.hstack((batch_ind, rois))
            rois_blob = np.vstack((rois_blob, rois_blob_this_image))

            # Add to labels, bbox targets, and bbox loss blobs
            labels_blob = np.hstack((labels_blob, labels))
            bbox_targets_blob = np.vstack((bbox_targets_blob, bbox_targets))
            bbox_inside_blob = np.vstack((bbox_inside_blob, bbox_inside_weights))
            # all_overlaps = np.hstack((all_overlaps, overlaps))

        # For debug visualizations
        # _vis_minibatch(im_blob, rois_blob, labels_blob, all_overlaps)

        blobs['rois'] = rois_blob
        blobs['labels'] = labels_blob

        if cfg.TRAIN.BBOX_REG:
            blobs['bbox_targets'] = bbox_targets_blob
            blobs['bbox_inside_weights'] = bbox_inside_blob
            blobs['bbox_outside_weights'] = \
                np.array(bbox_inside_blob > 0).astype(np.float32)

    return blobs


下面看看具体是如何读取图片数据的:

def _get_image_blob(roidb, scale_inds):这个函数其实就是读取图片,然后做尺寸变换,然后存储成4维矩阵的形式,返回;


def _get_image_blob(roidb, scale_inds):
    """Builds an input blob from the images in the roidb at the specified
    scales.
    """
    num_images = len(roidb)
    processed_ims = []
    im_scales = []
    for i in xrange(num_images):
        im = cv2.imread(roidb[i]['image'])#读取图片,返回的是一个ndarray的三维的矩阵
        if roidb[i]['flipped']:#如果这张图片是水平对称的数据,那么将三维矩阵中的第二维数据(宽)做对称操作
            im = im[:, ::-1, :]
        target_size = cfg.TRAIN.SCALES[scale_inds[i]]#确定选定的缩放的(最短边)尺寸的大小
        im, im_scale = prep_im_for_blob(im, cfg.PIXEL_MEANS, target_size,
                                        cfg.TRAIN.MAX_SIZE)#调用函数对图片进行缩放
        im_scales.append(im_scale)#把缩放系数,放到list中
        processed_ims.append(im)#把三维矩阵数据作为一个元素放到list中

    # Create a blob to hold the input images
    blob = im_list_to_blob(processed_ims)#调用函数,把前面在list中的三维矩阵元素,转换成4维矩阵的形式

    return blob, im_scales

在下面的函数中,作者将list中的3维的元素,转换成了4维的ndarray,下面看看作者是如何做的:

def im_list_to_blob(ims):#这里输入的ims是一个list,其中的每个元素是一个3维的图片矩阵数据
    """Convert a list of images into a network input.

    Assumes images are already prepared (means subtracted, BGR order, ...).
    """
    max_shape = np.array([im.shape for im in ims]).max(axis=0)#统计所有图片的height width的最大值
    num_images = len(ims)
    blob = np.zeros((num_images, max_shape[0], max_shape[1], 3),
                    dtype=np.float32)#构造一个全部为0的4维的矩阵,暂时的顺序是图片、高、宽、通道
    for i in xrange(num_images):
        im = ims[i]
        blob[i, 0:im.shape[0], 0:im.shape[1], :] = im #把每个图片对应的数据copy到blob中
    # Move channels (axis 3) to axis 1
    # Axis order will become: (batch elem, channel, height, width)
    channel_swap = (0, 3, 1, 2)#设置矩阵维度变换的参数,最终的4个维度分别对应图片、通道、高、宽,这与caffe的blob的格式就保持一致了
    blob = blob.transpose(channel_swap)
    return blob




作者:香蕉麦乐迪--sloanqin--覃元元

你可能感兴趣的:(深度学习,机器学习)