boxes.py 9.37 KB
Newer Older
1
import torch
eellison's avatar
eellison committed
2
from torch import Tensor
3
from typing import Tuple
4
from ._box_convert import _box_cxcywh_to_xyxy, _box_xyxy_to_cxcywh, _box_xywh_to_xyxy, _box_xyxy_to_xywh
5
import torchvision
6
from torchvision.extension import _assert_has_ops
7
8


9
def nms(boxes: Tensor, scores: Tensor, iou_threshold: float) -> Tensor:
10
11
12
13
14
15
16
17
    """
    Performs non-maximum suppression (NMS) on the boxes according
    to their intersection-over-union (IoU).

    NMS iteratively removes lower scoring boxes which have an
    IoU greater than iou_threshold with another (higher scoring)
    box.

Francisco Massa's avatar
Francisco Massa committed
18
19
20
    If multiple boxes have the exact same score and satisfy the IoU
    criterion with respect to a reference box, the selected box is
    not guaranteed to be the same between CPU and GPU. This is similar
21
22
    to the behavior of argsort in PyTorch when repeated values are present.

23
24
    Args:
        boxes (Tensor[N, 4])): boxes to perform NMS on. They
25
26
            are expected to be in ``(x1, y1, x2, y2)`` format with ``0 <= x1 < x2`` and
            ``0 <= y1 < y2``.
27
28
        scores (Tensor[N]): scores for each one of the boxes
        iou_threshold (float): discards all overlapping boxes with IoU > iou_threshold
29

30
31
32
33
    Returns:
        keep (Tensor): int64 tensor with the indices
            of the elements that have been kept
            by NMS, sorted in decreasing order of scores
34
    """
35
    _assert_has_ops()
36
    return torch.ops.torchvision.nms(boxes, scores, iou_threshold)
37
38


39
@torch.jit._script_if_tracing
40
41
42
43
44
45
def batched_nms(
    boxes: Tensor,
    scores: Tensor,
    idxs: Tensor,
    iou_threshold: float,
) -> Tensor:
46
47
48
49
50
51
    """
    Performs non-maximum suppression in a batched fashion.

    Each index value correspond to a category, and NMS
    will not be applied between elements of different categories.

52
53
    Args:
        boxes (Tensor[N, 4]): boxes where NMS will be performed. They
54
55
            are expected to be in ``(x1, y1, x2, y2)`` format with ``0 <= x1 < x2`` and
            ``0 <= y1 < y2``.
56
57
58
        scores (Tensor[N]): scores for each one of the boxes
        idxs (Tensor[N]): indices of the categories for each one of the boxes.
        iou_threshold (float): discards all overlapping boxes with IoU > iou_threshold
59

60
61
62
63
    Returns:
        keep (Tensor): int64 tensor with the indices of
            the elements that have been kept by NMS, sorted
            in decreasing order of scores
64
    """
65
66
    if boxes.numel() == 0:
        return torch.empty((0,), dtype=torch.int64, device=boxes.device)
67
68
69
70
    # strategy: in order to perform NMS independently per class.
    # we add an offset to all the boxes. The offset is dependent
    # only on the class idx, and is large enough so that boxes
    # from different classes do not overlap
71
72
73
74
75
76
    else:
        max_coordinate = boxes.max()
        offsets = idxs.to(boxes) * (max_coordinate + torch.tensor(1).to(boxes))
        boxes_for_nms = boxes + offsets[:, None]
        keep = nms(boxes_for_nms, scores, iou_threshold)
        return keep
77
78


79
def remove_small_boxes(boxes: Tensor, min_size: float) -> Tensor:
80
81
82
    """
    Remove boxes which contains at least one side smaller than min_size.

83
    Args:
84
85
        boxes (Tensor[N, 4]): boxes in ``(x1, y1, x2, y2)`` format
            with ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
eellison's avatar
eellison committed
86
        min_size (float): minimum size
87
88
89
90
91

    Returns:
        keep (Tensor[K]): indices of the boxes that have both sides
            larger than min_size
    """
92
93
    ws, hs = boxes[:, 2] - boxes[:, 0], boxes[:, 3] - boxes[:, 1]
    keep = (ws >= min_size) & (hs >= min_size)
94
    keep = torch.where(keep)[0]
95
96
97
    return keep


98
def clip_boxes_to_image(boxes: Tensor, size: Tuple[int, int]) -> Tensor:
99
    """
100
101
    Clip boxes so that they lie inside an image of size `size`.

102
    Args:
103
104
        boxes (Tensor[N, 4]): boxes in ``(x1, y1, x2, y2)`` format
            with ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
105
        size (Tuple[height, width]): size of the image
106
107
108
109
110
111
112
113

    Returns:
        clipped_boxes (Tensor[N, 4])
    """
    dim = boxes.dim()
    boxes_x = boxes[..., 0::2]
    boxes_y = boxes[..., 1::2]
    height, width = size
114
115
116
117
118
119
120
121
122
123

    if torchvision._is_tracing():
        boxes_x = torch.max(boxes_x, torch.tensor(0, dtype=boxes.dtype, device=boxes.device))
        boxes_x = torch.min(boxes_x, torch.tensor(width, dtype=boxes.dtype, device=boxes.device))
        boxes_y = torch.max(boxes_y, torch.tensor(0, dtype=boxes.dtype, device=boxes.device))
        boxes_y = torch.min(boxes_y, torch.tensor(height, dtype=boxes.dtype, device=boxes.device))
    else:
        boxes_x = boxes_x.clamp(min=0, max=width)
        boxes_y = boxes_y.clamp(min=0, max=height)

124
125
126
127
    clipped_boxes = torch.stack((boxes_x, boxes_y), dim=dim)
    return clipped_boxes.reshape(boxes.shape)


128
129
130
131
132
133
134
135
136
137
138
139
def box_convert(boxes: Tensor, in_fmt: str, out_fmt: str) -> Tensor:
    """
    Converts boxes from given in_fmt to out_fmt.
    Supported in_fmt and out_fmt are:

    'xyxy': boxes are represented via corners, x1, y1 being top left and x2, y2 being bottom right.

    'xywh' : boxes are represented via corner, width and height, x1, y2 being top left, w, h being width and height.

    'cxcywh' : boxes are represented via centre, width and height, cx, cy being center of box, w, h
    being width and height.

140
    Args:
141
142
143
144
145
146
147
        boxes (Tensor[N, 4]): boxes which will be converted.
        in_fmt (str): Input format of given boxes. Supported formats are ['xyxy', 'xywh', 'cxcywh'].
        out_fmt (str): Output format of given boxes. Supported formats are ['xyxy', 'xywh', 'cxcywh']

    Returns:
        boxes (Tensor[N, 4]): Boxes into converted format.
    """
148

149
    allowed_fmts = ("xyxy", "xywh", "cxcywh")
150
151
    if in_fmt not in allowed_fmts or out_fmt not in allowed_fmts:
        raise ValueError("Unsupported Bounding Box Conversions for given in_fmt and out_fmt")
152
153

    if in_fmt == out_fmt:
154
        return boxes.clone()
155
156

    if in_fmt != 'xyxy' and out_fmt != 'xyxy':
157
        # convert to xyxy and change in_fmt xyxy
158
        if in_fmt == "xywh":
159
            boxes = _box_xywh_to_xyxy(boxes)
160
        elif in_fmt == "cxcywh":
161
162
163
164
165
166
167
168
169
170
171
172
173
174
            boxes = _box_cxcywh_to_xyxy(boxes)
        in_fmt = 'xyxy'

    if in_fmt == "xyxy":
        if out_fmt == "xywh":
            boxes = _box_xyxy_to_xywh(boxes)
        elif out_fmt == "cxcywh":
            boxes = _box_xyxy_to_cxcywh(boxes)
    elif out_fmt == "xyxy":
        if in_fmt == "xywh":
            boxes = _box_xywh_to_xyxy(boxes)
        elif in_fmt == "cxcywh":
            boxes = _box_cxcywh_to_xyxy(boxes)
    return boxes
175
176


177
178
179
180
181
182
183
184
def _upcast(t: Tensor) -> Tensor:
    # Protects from numerical overflows in multiplications by upcasting to the equivalent higher type
    if t.is_floating_point():
        return t if t.dtype in (torch.float32, torch.float64) else t.float()
    else:
        return t if t.dtype in (torch.int32, torch.int64) else t.int()


185
def box_area(boxes: Tensor) -> Tensor:
186
187
    """
    Computes the area of a set of bounding boxes, which are specified by its
188
    (x1, y1, x2, y2) coordinates.
189

190
    Args:
191
        boxes (Tensor[N, 4]): boxes for which the area will be computed. They
192
193
            are expected to be in (x1, y1, x2, y2) format with
            ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
194
195
196
197

    Returns:
        area (Tensor[N]): area for each box
    """
198
    boxes = _upcast(boxes)
199
200
201
202
203
    return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])


# implementation from https://github.com/kuangliu/torchcv/blob/master/torchcv/utils/box.py
# with slight modifications
204
205
206
207
208
209
210
def _box_inter_union(boxes1: Tensor, boxes2: Tensor) -> Tuple[Tensor, Tensor]:
    area1 = box_area(boxes1)
    area2 = box_area(boxes2)

    lt = torch.max(boxes1[:, None, :2], boxes2[:, :2])  # [N,M,2]
    rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:])  # [N,M,2]

211
    wh = _upcast(rb - lt).clamp(min=0)  # [N,M,2]
212
213
214
215
216
217
218
    inter = wh[:, :, 0] * wh[:, :, 1]  # [N,M]

    union = area1[:, None] + area2 - inter

    return inter, union


219
def box_iou(boxes1: Tensor, boxes2: Tensor) -> Tensor:
220
221
222
    """
    Return intersection-over-union (Jaccard index) of boxes.

223
224
    Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with
    ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
225

226
    Args:
227
228
229
230
        boxes1 (Tensor[N, 4])
        boxes2 (Tensor[M, 4])

    Returns:
Aditya Oke's avatar
Aditya Oke committed
231
        iou (Tensor[N, M]): the NxM matrix containing the pairwise IoU values for every element in boxes1 and boxes2
232
    """
233
234
    inter, union = _box_inter_union(boxes1, boxes2)
    iou = inter / union
235
    return iou
Aditya Oke's avatar
Aditya Oke committed
236
237
238
239
240
241
242


# Implementation adapted from https://github.com/facebookresearch/detr/blob/master/util/box_ops.py
def generalized_box_iou(boxes1: Tensor, boxes2: Tensor) -> Tensor:
    """
    Return generalized intersection-over-union (Jaccard index) of boxes.

243
244
    Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with
    ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
Aditya Oke's avatar
Aditya Oke committed
245

246
    Args:
Aditya Oke's avatar
Aditya Oke committed
247
248
249
250
251
252
253
254
255
256
257
258
259
        boxes1 (Tensor[N, 4])
        boxes2 (Tensor[M, 4])

    Returns:
        generalized_iou (Tensor[N, M]): the NxM matrix containing the pairwise generalized_IoU values
        for every element in boxes1 and boxes2
    """

    # degenerate boxes gives inf / nan results
    # so do an early check
    assert (boxes1[:, 2:] >= boxes1[:, :2]).all()
    assert (boxes2[:, 2:] >= boxes2[:, :2]).all()

260
    inter, union = _box_inter_union(boxes1, boxes2)
Aditya Oke's avatar
Aditya Oke committed
261
262
263
264
265
    iou = inter / union

    lti = torch.min(boxes1[:, None, :2], boxes2[:, :2])
    rbi = torch.max(boxes1[:, None, 2:], boxes2[:, 2:])

266
    whi = _upcast(rbi - lti).clamp(min=0)  # [N,M,2]
Aditya Oke's avatar
Aditya Oke committed
267
268
269
    areai = whi[:, :, 0] * whi[:, :, 1]

    return iou - (areai - union) / areai