def test_anchor(h=40, w=40): x = nd.random_uniform(shape=(1, 3, h, w)) y = MultiBoxPrior(x, sizes=[0.5, 0.25, 0.1], ratios=[1, 2, 0.5]) boxes = y.reshape((h, w, -1, 4)) print('The first anchor box at row 21, column 21:', boxes[20, 20, 0, :]) return boxes
import mxnet as mx from mxnet import nd from mxnet.contrib.ndarray import MultiBoxPrior import matplotlib.pyplot as plt n = 40 # shape: batch x channel x height x weight x = nd.random_uniform(shape=(1, 3, n, n)) y = MultiBoxPrior(x, sizes=[.5, .25, .1], ratios=[1, 2, .5]) # the first anchor box generated for pixel at (20,20) # its format is (x_min, y_min, x_max, y_max) boxes = y.reshape((n, n, -1, 4)) print('The first anchor box at row 21, column 21:', boxes[20, 20, 0, :]) from mxnet.gluon import nn def class_predictor(num_anchors, num_classes): """return a layer to predict classes""" return nn.Conv2D(num_anchors * (num_classes + 1), 3, padding=1) cls_pred = class_predictor(5, 10) cls_pred.initialize() x = nd.zeros((2, 3, 20, 20)) print('Class prediction', cls_pred(x).shape) def box_predictor(num_anchors): """return a layer to predict delta locations""" return nn.Conv2D(num_anchors * 4, 3, padding=1) box_pred = box_predictor(10)
#!/usr/bin/env python #-*- coding:utf-8 -*- import mxnet as mx from mxnet import nd from mxnet.contrib.ndarray import MultiBoxPrior##MultiBoxPrior产生预设框 n = 40 # 输入形状: batch × channel × height × weight x = nd.random_uniform(shape=(1, 3, n, n)) ## 图像 n 个预设尺寸 m 个预设的长宽比 输出为 n+m-1 个方框 y = MultiBoxPrior(x, sizes=[.5, .25, .1], ratios=[1, 2, .5]) ## 取位于 (20,20) 像素点的第一个预设框 # box的格式为 (x_min, y_min, x_max, y_max) 且为比例 boxes = y.reshape((n, n, -1, 4)) print('The first anchor box at row 21, column 21:', boxes[20, 20, 0, :]) import matplotlib.pyplot as plt #"""convert an anchor box to a matplotlib rectangle""" def box_to_rect(box, color, linewidth=3): box = box.asnumpy() return plt.Rectangle( (box[0], box[1]), (box[2]-box[0]), (box[3]-box[1]), fill=False, edgecolor=color, linewidth=linewidth) colors = ['blue', 'green', 'red', 'black', 'magenta']# 3+3-1=5个 plt.imshow(nd.ones((n, n, 3)).asnumpy()) anchors = boxes[20, 20, :, :] for i in range(anchors.shape[0]): plt.gca().add_patch(box_to_rect(anchors[i,:]*n, colors[i])) plt.show()