|
| 1 | +from __future__ import division |
| 2 | + |
| 3 | +import numpy as np |
| 4 | + |
| 5 | +import chainer |
| 6 | +from chainer.backends import cuda |
| 7 | + |
| 8 | +from chainercv import transforms |
| 9 | + |
| 10 | + |
| 11 | +class FasterRCNN(chainer.Chain): |
| 12 | + """Base class of Feature Pyramid Networks. |
| 13 | +
|
| 14 | + This is a base class of Feature Pyramid Networks [#]_. |
| 15 | +
|
| 16 | + .. [#] Tsung-Yi Lin et al. |
| 17 | + Feature Pyramid Networks for Object Detection. CVPR 2017 |
| 18 | +
|
| 19 | + Args: |
| 20 | + extractor (Link): A link that extracts feature maps. |
| 21 | + This link must have :obj:`scales`, :obj:`mean` and |
| 22 | + :meth:`__call__`. |
| 23 | + rpn (Link): A link that has the same interface as |
| 24 | + :class:`~chainercv.links.model.fpn.RPN`. |
| 25 | + Please refer to the documentation found there. |
| 26 | + head (Link): A link that has the same interface as |
| 27 | + :class:`~chainercv.links.model.fpn.Head`. |
| 28 | + Please refer to the documentation found there. |
| 29 | +
|
| 30 | + Parameters: |
| 31 | + nms_thresh (float): The threshold value |
| 32 | + for :func:`~chainercv.utils.non_maximum_suppression`. |
| 33 | + The default value is :obj:`0.45`. |
| 34 | + This value can be changed directly or by using :meth:`use_preset`. |
| 35 | + score_thresh (float): The threshold value for confidence score. |
| 36 | + If a bounding box whose confidence score is lower than this value, |
| 37 | + the bounding box will be suppressed. |
| 38 | + The default value is :obj:`0.6`. |
| 39 | + This value can be changed directly or by using :meth:`use_preset`. |
| 40 | +
|
| 41 | + """ |
| 42 | + |
| 43 | + _min_size = 800 |
| 44 | + _max_size = 1333 |
| 45 | + _stride = 32 |
| 46 | + |
| 47 | + def __init__(self, extractor, rpn, head): |
| 48 | + super(FasterRCNN, self).__init__() |
| 49 | + with self.init_scope(): |
| 50 | + self.extractor = extractor |
| 51 | + self.rpn = rpn |
| 52 | + self.head = head |
| 53 | + |
| 54 | + self.use_preset('visualize') |
| 55 | + |
| 56 | + def use_preset(self, preset): |
| 57 | + """Use the given preset during prediction. |
| 58 | +
|
| 59 | + This method changes values of :obj:`nms_thresh` and |
| 60 | + :obj:`score_thresh`. These values are a threshold value |
| 61 | + used for non maximum suppression and a threshold value |
| 62 | + to discard low confidence proposals in :meth:`predict`, |
| 63 | + respectively. |
| 64 | +
|
| 65 | + If the attributes need to be changed to something |
| 66 | + other than the values provided in the presets, please modify |
| 67 | + them by directly accessing the public attributes. |
| 68 | +
|
| 69 | + Args: |
| 70 | + preset ({'visualize', 'evaluate'}): A string to determine the |
| 71 | + preset to use. |
| 72 | + """ |
| 73 | + |
| 74 | + if preset == 'visualize': |
| 75 | + self.nms_thresh = 0.5 |
| 76 | + self.score_thresh = 0.7 |
| 77 | + elif preset == 'evaluate': |
| 78 | + self.nms_thresh = 0.5 |
| 79 | + self.score_thresh = 0.05 |
| 80 | + else: |
| 81 | + raise ValueError('preset must be visualize or evaluate') |
| 82 | + |
| 83 | + def __call__(self, x): |
| 84 | + assert(not chainer.config.train) |
| 85 | + hs = self.extractor(x) |
| 86 | + rpn_locs, rpn_confs = self.rpn(hs) |
| 87 | + anchors = self.rpn.anchors(h.shape[2:] for h in hs) |
| 88 | + rois, roi_indices = self.rpn.decode( |
| 89 | + rpn_locs, rpn_confs, anchors, x.shape) |
| 90 | + rois, roi_indices = self.head.distribute(rois, roi_indices) |
| 91 | + head_locs, head_confs = self.head(hs, rois, roi_indices) |
| 92 | + return rois, roi_indices, head_locs, head_confs |
| 93 | + |
| 94 | + def predict(self, imgs): |
| 95 | + """Detect objects from images. |
| 96 | +
|
| 97 | + This method predicts objects for each image. |
| 98 | +
|
| 99 | + Args: |
| 100 | + imgs (iterable of numpy.ndarray): Arrays holding images. |
| 101 | + All images are in CHW and RGB format |
| 102 | + and the range of their value is :math:`[0, 255]`. |
| 103 | +
|
| 104 | + Returns: |
| 105 | + tuple of lists: |
| 106 | + This method returns a tuple of three lists, |
| 107 | + :obj:`(bboxes, labels, scores)`. |
| 108 | +
|
| 109 | + * **bboxes**: A list of float arrays of shape :math:`(R, 4)`, \ |
| 110 | + where :math:`R` is the number of bounding boxes in a image. \ |
| 111 | + Each bounding box is organized by \ |
| 112 | + :math:`(y_{min}, x_{min}, y_{max}, x_{max})` \ |
| 113 | + in the second axis. |
| 114 | + * **labels** : A list of integer arrays of shape :math:`(R,)`. \ |
| 115 | + Each value indicates the class of the bounding box. \ |
| 116 | + Values are in range :math:`[0, L - 1]`, where :math:`L` is the \ |
| 117 | + number of the foreground classes. |
| 118 | + * **scores** : A list of float arrays of shape :math:`(R,)`. \ |
| 119 | + Each value indicates how confident the prediction is. |
| 120 | +
|
| 121 | + """ |
| 122 | + |
| 123 | + sizes = [img.shape[1:] for img in imgs] |
| 124 | + x, scales = self.prepare(imgs) |
| 125 | + |
| 126 | + with chainer.using_config('train', False), chainer.no_backprop_mode(): |
| 127 | + rois, roi_indices, head_locs, head_confs = self(x) |
| 128 | + bboxes, labels, scores = self.head.decode( |
| 129 | + rois, roi_indices, head_locs, head_confs, |
| 130 | + scales, sizes, self.nms_thresh, self.score_thresh) |
| 131 | + |
| 132 | + bboxes = [cuda.to_cpu(bbox) for bbox in bboxes] |
| 133 | + labels = [cuda.to_cpu(label) for label in labels] |
| 134 | + scores = [cuda.to_cpu(score) for score in scores] |
| 135 | + return bboxes, labels, scores |
| 136 | + |
| 137 | + def prepare(self, imgs): |
| 138 | + """Preprocess images. |
| 139 | +
|
| 140 | + Args: |
| 141 | + imgs (iterable of numpy.ndarray): Arrays holding images. |
| 142 | + All images are in CHW and RGB format |
| 143 | + and the range of their value is :math:`[0, 255]`. |
| 144 | +
|
| 145 | + Returns: |
| 146 | + Two arrays: preprocessed images and \ |
| 147 | + scales that were caluclated in prepocessing. |
| 148 | +
|
| 149 | + """ |
| 150 | + |
| 151 | + scales = [] |
| 152 | + resized_imgs = [] |
| 153 | + for img in imgs: |
| 154 | + _, H, W = img.shape |
| 155 | + scale = self._min_size / min(H, W) |
| 156 | + if scale * max(H, W) > self._max_size: |
| 157 | + scale = self._max_size / max(H, W) |
| 158 | + scales.append(scale) |
| 159 | + H, W = int(H * scale), int(W * scale) |
| 160 | + img = transforms.resize(img, (H, W)) |
| 161 | + img -= self.extractor.mean |
| 162 | + resized_imgs.append(img) |
| 163 | + |
| 164 | + size = np.array([im.shape[1:] for im in resized_imgs]).max(axis=0) |
| 165 | + size = (np.ceil(size / self._stride) * self._stride).astype(int) |
| 166 | + x = np.zeros((len(imgs), 3, size[0], size[1]), dtype=np.float32) |
| 167 | + for i, img in enumerate(resized_imgs): |
| 168 | + _, H, W = img.shape |
| 169 | + x[i, :, :H, :W] = img |
| 170 | + |
| 171 | + x = self.xp.array(x) |
| 172 | + return x, scales |
0 commit comments