第14章コンピュータビジョン
14.4.4. Predicting Bounding Boxes with Non-Maximum Suppression14.4.4 非最大値抑制による境界ボックスの予測
During prediction, we generate multiple anchor boxes for the image and predict classes and offsets for each of them. A predicted bounding box is thus obtained according to an anchor box with its predicted offset. Below we implement the
offset_inverse function that takes in anchors and offset predictions as inputs and applies inverse offset transformations to return the predicted bounding box coordinates.英語のヒント
予測のあいだは、画像について複数のアンカーボックスを生成し、それぞれのクラスとオフセットを予測する。こうして、予測したオフセットをもつアンカーボックスに従って、予測した境界ボックスが得られる。下では、アンカーとオフセットの予測を入力としてとり、逆のオフセット変換を当てはめて予測した境界ボックスの座標を返す
offset_inverse関数を実装する。#@save
def offset_inverse(anchors, offset_preds):
"""Predict bounding boxes based on anchor boxes with predicted offsets."""
anc = d2l.box_corner_to_center(anchors)
pred_bbox_xy = (offset_preds[:, :2] * anc[:, 2:] / 10) + anc[:, :2]
pred_bbox_wh = torch.exp(offset_preds[:, 2:] / 5) * anc[:, 2:]
pred_bbox = torch.cat((pred_bbox_xy, pred_bbox_wh), axis=1)
predicted_bbox = d2l.box_center_to_corner(pred_bbox)
return predicted_bboxWhen there are many anchor boxes, many similar (with significant overlap) predicted bounding boxes can be potentially output for surrounding the same object. To simplify the output, we can merge similar predicted bounding boxes that belong to the same object by using non-maximum suppression (NMS).
英語のヒント
アンカーボックスがたくさんあると、同じ物体を囲む、よく似た(大きく重なる)予測した境界ボックスがたくさん出力されるかもしれない。出力を簡単にするため、非最大値抑制(NMS)を使って、同じ物体に属するよく似た予測した境界ボックスをまとめられる。
Here is how non-maximum suppression works. For a predicted bounding box , the object detection model calculates the predicted likelihood for each class. Denoting by the largest predicted likelihood, the class corresponding to this probability is the predicted class for . Specifically, we refer to as the confidence (score) of the predicted bounding box . On the same image, all the predicted non-background bounding boxes are sorted by confidence in descending order to generate a list . Then we manipulate the sorted list in the following steps:
英語のヒント
非最大値抑制は次のように働く。予測した境界ボックスについて、物体検出モデルは各クラスの予測した尤度を計算する。予測した尤度の最大値をで表すと、この確率に対応するクラスがの予測したクラスである。具体的には、を予測した境界ボックスの信頼度(スコア)と呼ぶ。同じ画像で、背景以外のすべての予測した境界ボックスを信頼度の降順に並べ、リストを作る。それから、並べたリストを次の手順で操作する。
- Select the predicted bounding box with the highest confidence from as a basis and remove all non-basis predicted bounding boxes whose IoU with exceeds a predefined threshold from . At this point, keeps the predicted bounding box with the highest confidence but drops others that are too similar to it. In a nutshell, those with non-maximum confidence scores are suppressed.
英語のヒント
から信頼度が最も高い予測した境界ボックスを基準として選び、とのIoUがあらかじめ決めた閾値を超える、基準でない予測した境界ボックスをすべてから取り除く。この時点で、は信頼度が最も高い予測した境界ボックスを残し、それとよく似すぎたほかのものを捨てている。手短に言えば、信頼度のスコアが最大でないものが抑制される。 - Select the predicted bounding box with the second highest confidence from as another basis and remove all non-basis predicted bounding boxes whose IoU with exceeds from .
英語のヒント
から信頼度が2番目に高い予測した境界ボックスを別の基準として選び、とのIoUがを超える、基準でない予測した境界ボックスをすべてから取り除く。 - Repeat the above process until all the predicted bounding boxes in have been used as a basis. At this time, the IoU of any pair of predicted bounding boxes in is below the threshold ; thus, no pair is too similar with each other.
英語のヒント
のすべての予測した境界ボックスが基準として使われるまで、上の過程を繰り返す。このとき、の予測した境界ボックスのどの組のIoUも閾値を下回る。したがって、互いに似すぎた組はない。 - Output all the predicted bounding boxes in the list .
英語のヒント
リストのすべての予測した境界ボックスを出力する。
The following
nms function sorts confidence scores in descending order and returns their indices.英語のヒント
次の
nms関数は、信頼度のスコアを降順に並べ、その添字を返す。#@save
def nms(boxes, scores, iou_threshold):
"""Sort confidence scores of predicted bounding boxes."""
B = torch.argsort(scores, dim=-1, descending=True)
keep = [] # Indices of predicted bounding boxes that will be kept
while B.numel() > 0:
i = B[0]
keep.append(i)
if B.numel() == 1: break
iou = box_iou(boxes[i, :].reshape(-1, 4),
boxes[B[1:], :].reshape(-1, 4)).reshape(-1)
inds = torch.nonzero(iou <= iou_threshold).reshape(-1)
B = B[inds + 1]
return torch.tensor(keep, device=boxes.device)We define the following
multibox_detection to apply non-maximum suppression to predicting bounding boxes. Do not worry if you find the implementation a bit complicated: we will show how it works with a concrete example right after the implementation.英語のヒント
境界ボックスの予測に非最大値抑制を当てはめるため、次の
multibox_detectionを定義する。実装が少し複雑だと感じても心配はいらない。実装のすぐ後で、具体的な例でそれがどう働くかを示す。#@save
def multibox_detection(cls_probs, offset_preds, anchors, nms_threshold=0.5,
pos_threshold=0.009999999):
"""Predict bounding boxes using non-maximum suppression."""
device, batch_size = cls_probs.device, cls_probs.shape[0]
anchors = anchors.squeeze(0)
num_classes, num_anchors = cls_probs.shape[1], cls_probs.shape[2]
out = []
for i in range(batch_size):
cls_prob, offset_pred = cls_probs[i], offset_preds[i].reshape(-1, 4)
conf, class_id = torch.max(cls_prob[1:], 0)
predicted_bb = offset_inverse(anchors, offset_pred)
keep = nms(predicted_bb, conf, nms_threshold)
# Find all non-`keep` indices and set the class to background
all_idx = torch.arange(num_anchors, dtype=torch.long, device=device)
combined = torch.cat((keep, all_idx))
uniques, counts = combined.unique(return_counts=True)
non_keep = uniques[counts == 1]
all_id_sorted = torch.cat((keep, non_keep))
class_id[non_keep] = -1
class_id = class_id[all_id_sorted]
conf, predicted_bb = conf[all_id_sorted], predicted_bb[all_id_sorted]
# Here `pos_threshold` is a threshold for positive (non-background)
# predictions
below_min_idx = (conf < pos_threshold)
class_id[below_min_idx] = -1
conf[below_min_idx] = 1 - conf[below_min_idx]
pred_info = torch.cat((class_id.unsqueeze(1),
conf.unsqueeze(1),
predicted_bb), dim=1)
out.append(pred_info)
return torch.stack(out)Now let’s apply the above implementations to a concrete example with four anchor boxes. For simplicity, we assume that the predicted offsets are all zeros. This means that the predicted bounding boxes are anchor boxes. For each class among the background, dog, and cat, we also define its predicted likelihood.
英語のヒント
では、上の実装を、四つのアンカーボックスがある具体的な例に当てはめよう。簡単のため、予測したオフセットはすべてゼロとする。これは、予測した境界ボックスがアンカーボックスそのものであることを意味する。背景、犬、猫の各クラスについて、予測した尤度も定義する。
anchors = torch.tensor([[0.1, 0.08, 0.52, 0.92], [0.08, 0.2, 0.56, 0.95],
[0.15, 0.3, 0.62, 0.91], [0.55, 0.2, 0.9, 0.88]])
offset_preds = torch.tensor([0] * anchors.numel())
cls_probs = torch.tensor([[0] * 4, # Predicted background likelihood
[0.9, 0.8, 0.7, 0.1], # Predicted dog likelihood
[0.1, 0.2, 0.3, 0.9]]) # Predicted cat likelihoodWe can plot these predicted bounding boxes with their confidence on the image.
英語のヒント
これらの予測した境界ボックスを、その信頼度とともに画像に描ける。
fig = d2l.plt.imshow(img)
show_bboxes(fig.axes, anchors * bbox_scale,
['dog=0.9', 'dog=0.8', 'dog=0.7', 'cat=0.9'])Now we can invoke the
multibox_detection function to perform non-maximum suppression, where the threshold is set to 0.5. Note that we add a dimension for examples in the tensor input.英語のヒント
これで、
multibox_detection関数を呼び出して非最大値抑制を行える。閾値は0.5に設定する。テンソルの入力に事例のための次元を加えることに注意してほしい。We can see that the shape of the returned result is (batch size, number of anchor boxes, 6). The six elements in the innermost dimension gives the output information for the same predicted bounding box. The first element is the predicted class index, which starts from 0 (0 is dog and 1 is cat). The value -1 indicates background or removal in non-maximum suppression. The second element is the confidence of the predicted bounding box. The remaining four elements are the -axis coordinates of the upper-left corner and the lower-right corner of the predicted bounding box, respectively (range is between 0 and 1).
英語のヒント
返された結果の形状は(バッチの大きさ、アンカーボックスの数、6)であることがわかる。最も内側の次元の六つの要素は、同じ予測した境界ボックスについての出力の情報を与える。最初の要素は予測したクラスの添字で、0から始まる(0は犬、1は猫)。値−1は、背景か、非最大値抑制で取り除かれたことを示す。2番目の要素は、予測した境界ボックスの信頼度である。残りの四つの要素は、それぞれ予測した境界ボックスの左上の角と右下の角の軸座標である(範囲は0から1)。
output = multibox_detection(cls_probs.unsqueeze(dim=0),
offset_preds.unsqueeze(dim=0),
anchors.unsqueeze(dim=0),
nms_threshold=0.5)
outputtensor([[[ 0.00, 0.90, 0.10, 0.08, 0.52, 0.92],
[ 1.00, 0.90, 0.55, 0.20, 0.90, 0.88],
[-1.00, 0.80, 0.08, 0.20, 0.56, 0.95],
[-1.00, 0.70, 0.15, 0.30, 0.62, 0.91]]])After removing those predicted bounding boxes of class -1, we can output the final predicted bounding box kept by non-maximum suppression.
英語のヒント
クラスが−1の予測した境界ボックスを取り除いた後、非最大値抑制で残った最終的な予測した境界ボックスを出力できる。
fig = d2l.plt.imshow(img)
for i in output[0].detach().numpy():
if i[0] == -1:
continue
label = ('dog=', 'cat=')[int(i[0])] + str(i[1])
show_bboxes(fig.axes, [torch.tensor(i[2:]) * bbox_scale], label)In practice, we can remove predicted bounding boxes with lower confidence even before performing non-maximum suppression, thereby reducing computation in this algorithm. We may also post-process the output of non-maximum suppression, for example, by only keeping results with higher confidence in the final output.
英語のヒント
実際には、非最大値抑制を行う前にさえ、信頼度の低い予測した境界ボックスを取り除いて、このアルゴリズムの計算を減らせる。また、たとえば最終的な出力で信頼度の高い結果だけを残すことで、非最大値抑制の出力を後処理することもできる。