|
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- # @Created : 2021/04/21
- # @Author : Koala
- # @FileName: utils.py
-
- import torch
- import numpy as np
-
- def xywh2xyxy(x):
- y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
- y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x
- y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y
- y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x
- y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y
- return y
-
- def box_iou(box1, box2):
- def box_area(box):
- return (box[2] - box[0]) * (box[3] - box[1])
-
- area1 = box_area(box1.T)
- area2 = box_area(box2.T)
-
- inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
- return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter)
-
-
- def IoU(box1: np.ndarray, box2: np.ndarray, in_area=True) -> np.ndarray:
- assert box1.ndim == 2 and box2.ndim == 2
- box1 = box1[:, np.newaxis, :]
- box2 = box2[np.newaxis, :, :]
- area1 = (box1[..., 2] - box1[..., 0]) * (box1[..., 3] - box1[..., 1])
- area2 = (box2[..., 2] - box2[..., 0]) * (box2[..., 3] - box2[..., 1])
- max_xy = np.maximum(box1[..., :2], box2[..., :2])
- min_xy = np.minimum(box1[..., 2:4], box2[..., 2:4])
- inter = np.clip(min_xy[..., 0] - max_xy[..., 0], 0, None) * np.clip(min_xy[..., 1] - max_xy[..., 1], 0, None)
- if in_area:
- return inter / area1
- else:
- return inter / (area1 + area2 - inter)
|