第14章コンピュータビジョン
14.4.1. Generating Multiple Anchor Boxes14.4.1 複数のアンカーボックスを生成する
Suppose that the input image has a height of and width of . We generate anchor boxes with different shapes centered on each pixel of the image. Let the scale be and the aspect ratio (ratio of width to height) is . Then the width and height of the anchor box are and , respectively. Note that when the center position is given, an anchor box with known width and height is determined.
英語のヒント
入力画像の高さが、幅がだとする。画像の各画素を中心として、さまざまな形のアンカーボックスを生成する。縮尺を、縦横比(幅と高さの比)をとする。すると、アンカーボックスの幅と高さはそれぞれとになる。中心の位置が与えられれば、幅と高さがわかっているアンカーボックスは決まることに注意してほしい。
To generate multiple anchor boxes with different shapes, let’s set a series of scales and a series of aspect ratios . When using all the combinations of these scales and aspect ratios with each pixel as the center, the input image will have a total of anchor boxes. Although these anchor boxes may cover all the ground-truth bounding boxes, the computational complexity is easily too high. In practice, we can only consider those combinations containing or :
英語のヒント
さまざまな形の複数のアンカーボックスを生成するため、一連の縮尺と一連の縦横比を設定しよう。各画素を中心として、これらの縮尺と縦横比のすべての組み合わせを使うと、入力画像には合計個のアンカーボックスができる。これらのアンカーボックスは正解の境界ボックスをすべてカバーするかもしれないが、計算の複雑さがすぐに高くなりすぎる。実際には、次のような、かを含む組み合わせだけを考えればよい。
(14.4.1)
That is to say, the number of anchor boxes centered on the same pixel is . For the entire input image, we will generate a total of anchor boxes.
英語のヒント
つまり、同じ画素を中心とするアンカーボックスの数はである。入力画像全体については、合計個のアンカーボックスを生成する。
The above method of generating anchor boxes is implemented in the following
multibox_prior function. We specify the input image, a list of scales, and a list of aspect ratios, then this function will return all the anchor boxes.英語のヒント
上のアンカーボックスを生成する方法は、次の
multibox_prior関数で実装されている。入力画像、縮尺のリスト、縦横比のリストを指定すると、この関数はすべてのアンカーボックスを返す。#@save
def multibox_prior(data, sizes, ratios):
"""Generate anchor boxes with different shapes centered on each pixel."""
in_height, in_width = data.shape[-2:]
device, num_sizes, num_ratios = data.device, len(sizes), len(ratios)
boxes_per_pixel = (num_sizes + num_ratios - 1)
size_tensor = torch.tensor(sizes, device=device)
ratio_tensor = torch.tensor(ratios, device=device)
# Offsets are required to move the anchor to the center of a pixel. Since
# a pixel has height=1 and width=1, we choose to offset our centers by 0.5
offset_h, offset_w = 0.5, 0.5
steps_h = 1.0 / in_height # Scaled steps in y axis
steps_w = 1.0 / in_width # Scaled steps in x axis
# Generate all center points for the anchor boxes
center_h = (torch.arange(in_height, device=device) + offset_h) * steps_h
center_w = (torch.arange(in_width, device=device) + offset_w) * steps_w
shift_y, shift_x = torch.meshgrid(center_h, center_w, indexing='ij')
shift_y, shift_x = shift_y.reshape(-1), shift_x.reshape(-1)
# Generate `boxes_per_pixel` number of heights and widths that are later
# used to create anchor box corner coordinates (xmin, xmax, ymin, ymax)
w = torch.cat((size_tensor * torch.sqrt(ratio_tensor[0]),
sizes[0] * torch.sqrt(ratio_tensor[1:])))\
* in_height / in_width # Handle rectangular inputs
h = torch.cat((size_tensor / torch.sqrt(ratio_tensor[0]),
sizes[0] / torch.sqrt(ratio_tensor[1:])))
# Divide by 2 to get half height and half width
anchor_manipulations = torch.stack((-w, -h, w, h)).T.repeat(
in_height * in_width, 1) / 2
# Each center point will have `boxes_per_pixel` number of anchor boxes, so
# generate a grid of all anchor box centers with `boxes_per_pixel` repeats
out_grid = torch.stack([shift_x, shift_y, shift_x, shift_y],
dim=1).repeat_interleave(boxes_per_pixel, dim=0)
output = out_grid + anchor_manipulations
return output.unsqueeze(0)We can see that the shape of the returned anchor box variable
Y is (batch size, number of anchor boxes, 4).英語のヒント
返されたアンカーボックスの変数
Yの形状は(バッチの大きさ、アンカーボックスの数、4)であることがわかる。img = d2l.plt.imread('../img/catdog.jpg')
h, w = img.shape[:2]
print(h, w)
X = torch.rand(size=(1, 3, h, w)) # Construct input data
Y = multibox_prior(X, sizes=[0.75, 0.5, 0.25], ratios=[1, 2, 0.5])
Y.shape561 728torch.Size([1, 2042040, 4])After changing the shape of the anchor box variable
Y to (image height, image width, number of anchor boxes centered on the same pixel, 4), we can obtain all the anchor boxes centered on a specified pixel position. In the following, we access the first anchor box centered on (250, 250). It has four elements: the -axis coordinates at the upper-left corner and the -axis coordinates at the lower-right corner of the anchor box. The coordinate values of both axes are divided by the width and height of the image, respectively.英語のヒント
アンカーボックスの変数
Yの形状を(画像の高さ、画像の幅、同じ画素を中心とするアンカーボックスの数、4)に変えると、指定した画素の位置を中心とするすべてのアンカーボックスを得られる。以下では、(250, 250)を中心とする最初のアンカーボックスにアクセスする。それには四つの要素がある。アンカーボックスの左上の角の軸座標と、右下の角の軸座標である。両方の軸の座標の値は、それぞれ画像の幅と高さで割られている。boxes = Y.reshape(h, w, 5, 4)
boxes[250, 250, 0, :]tensor([0.06, 0.07, 0.63, 0.82])In order to show all the anchor boxes centered on one pixel in the image, we define the following
show_bboxes function to draw multiple bounding boxes on the image.英語のヒント
画像の一つの画素を中心とするすべてのアンカーボックスを示すため、画像に複数の境界ボックスを描く次の
show_bboxes関数を定義する。#@save
def show_bboxes(axes, bboxes, labels=None, colors=None):
"""Show bounding boxes."""
def make_list(obj, default_values=None):
if obj is None:
obj = default_values
elif not isinstance(obj, (list, tuple)):
obj = [obj]
return obj
labels = make_list(labels)
colors = make_list(colors, ['b', 'g', 'r', 'm', 'c'])
for i, bbox in enumerate(bboxes):
color = colors[i % len(colors)]
rect = d2l.bbox_to_rect(bbox.detach().numpy(), color)
axes.add_patch(rect)
if labels and len(labels) > i:
text_color = 'k' if color == 'w' else 'w'
axes.text(rect.xy[0], rect.xy[1], labels[i],
va='center', ha='center', fontsize=9, color=text_color,
bbox=dict(facecolor=color, lw=0))As we just saw, the coordinate values of the and axes in the variable
boxes have been divided by the width and height of the image, respectively. When drawing anchor boxes, we need to restore their original coordinate values; thus, we define variable bbox_scale below. Now, we can draw all the anchor boxes centered on (250, 250) in the image. As you can see, the blue anchor box with a scale of 0.75 and an aspect ratio of 1 well surrounds the dog in the image.英語のヒント
いま見たように、変数
boxesの軸と軸の座標の値は、それぞれ画像の幅と高さで割られている。アンカーボックスを描くときは、元の座標の値に戻す必要がある。そのため、下で変数bbox_scaleを定義する。これで、画像の中で(250, 250)を中心とするすべてのアンカーボックスを描ける。見てのとおり、縮尺0.75、縦横比1の青いアンカーボックスが、画像の中の犬をうまく囲んでいる。d2l.set_figsize()
bbox_scale = torch.tensor((w, h, w, h))
fig = d2l.plt.imshow(img)
show_bboxes(fig.axes, boxes[250, 250, :, :] * bbox_scale,
['s=0.75, r=1', 's=0.5, r=1', 's=0.25, r=1', 's=0.75, r=2',
's=0.75, r=0.5'])