|
- import numpy as np
- import mindspore as ms
- from mindspore import context
- from src.efficientdet.loss import FocalLoss
- from src.efficientdet.utils import Anchors
- context.set_context(mode=context.PYNATIVE_MODE, device_target="Ascend")
- # context.set_context(device_id=6, enable_auto_mixed_precision=True)
-
-
- def bbox_transform(anchors, regression):
-
- y_centers_a = (anchors[..., 0] + anchors[..., 2]) / 2
- x_centers_a = (anchors[..., 1] + anchors[..., 3]) / 2
- ha = anchors[..., 2] - anchors[..., 0]
- wa = anchors[..., 3] - anchors[..., 1]
-
- w = np.exp(regression[..., 3]) * wa
- h = np.exp(regression[..., 2]) * ha
-
- y_centers = regression[..., 0] * ha + y_centers_a
- x_centers = regression[..., 1] * wa + x_centers_a
-
- ymin = y_centers - h / 2.
- xmin = x_centers - w / 2.
- ymax = y_centers + h / 2.
- xmax = x_centers + w / 2.
-
- return np.stack([xmin, ymin, xmax, ymax], axis=2)
-
- def clipBoxes(boxes, img):
- batch_size, num_channels, height, width = img.shape
-
- boxes[:, :, 0] = np.clip(boxes[:, :, 0], a_min=0, a_max = None)
- boxes[:, :, 1] = np.clip(boxes[:, :, 1], a_min=0, a_max = None)
-
- boxes[:, :, 2] = np.clip(boxes[:, :, 2], a_min = None, a_max=width - 1)
- boxes[:, :, 3] = np.clip(boxes[:, :, 3], a_min = None, a_max=height - 1)
-
- return boxes
-
- def softmax(x, axis=None):
- x = x - x.max(axis=axis, keepdims=True)
- y = np.exp(x)
- return y / y.sum(axis=axis, keepdims=True)
-
- def sigmoid(x):
- return 1 / (1 + np.exp(-x))
-
- np.random.seed(1)
-
- # box = np.load("/data/efficientdet_ch/box.npy").astype(np.float32)
-
- padded_box = np.load("/data/efficientdet_ch/padded_box.npy").astype(np.float32)
-
- padded_box = np.expand_dims(padded_box, axis=0)
- padded_box = np.concatenate((padded_box, padded_box), 0)
-
-
- # padded_box = np.zeros([1,128,5]).astype(np.float32)
-
- img = np.load("/data/efficientdet_ch/img.npy").astype(np.float32)
- img = np.transpose(img, (2, 0, 1))
- img = np.expand_dims(img, axis=0)
- img = np.concatenate((img, img), 0)
-
- anchors = Anchors()(ms.Tensor(img))
-
- classifications = np.random.randn(2, 49104, 90).astype(np.float32)
- classifications = softmax(classifications, axis=2)
-
- regression = sigmoid(np.random.randn(2, 49104, 4).astype(np.float32))
-
- loss_cell = FocalLoss()
- loss = loss_cell(ms.Tensor(regression), ms.Tensor(classifications), ms.Tensor(anchors), ms.Tensor(padded_box))
-
- print(loss)
|