_meta.py 10.3 KB
Newer Older
1
from typing import List, Optional, Tuple
2

3
4
import PIL.Image
import torch
5
6
from torchvision import datapoints
from torchvision.datapoints import BoundingBoxFormat
7
from torchvision.transforms import _functional_pil as _FP
8

9
10
from torchvision.utils import _log_api_usage_once

11
from ._utils import _get_kernel, _register_kernel_internal, _register_unsupported_type, is_simple_tensor
12

13

14
@_register_unsupported_type(datapoints.BoundingBoxes, datapoints.Mask)
15
def get_dimensions(inpt: torch.Tensor) -> List[int]:
16
    if torch.jit.is_scripting():
17
        return get_dimensions_image_tensor(inpt)
18
19
20
21
22

    _log_api_usage_once(get_dimensions)

    kernel = _get_kernel(get_dimensions, type(inpt))
    return kernel(inpt)
23
24


25
@_register_kernel_internal(get_dimensions, torch.Tensor)
26
@_register_kernel_internal(get_dimensions, datapoints.Image, datapoint_wrapper=False)
27
28
29
30
31
32
33
34
35
36
37
38
def get_dimensions_image_tensor(image: torch.Tensor) -> List[int]:
    chw = list(image.shape[-3:])
    ndims = len(chw)
    if ndims == 3:
        return chw
    elif ndims == 2:
        chw.insert(0, 1)
        return chw
    else:
        raise TypeError(f"Input tensor should have at least two dimensions, but got {ndims}")


39
get_dimensions_image_pil = _register_kernel_internal(get_dimensions, PIL.Image.Image)(_FP.get_dimensions)
40
41


42
@_register_kernel_internal(get_dimensions, datapoints.Video, datapoint_wrapper=False)
Philip Meier's avatar
Philip Meier committed
43
44
45
46
def get_dimensions_video(video: torch.Tensor) -> List[int]:
    return get_dimensions_image_tensor(video)


47
@_register_unsupported_type(datapoints.BoundingBoxes, datapoints.Mask)
48
def get_num_channels(inpt: torch.Tensor) -> int:
49
    if torch.jit.is_scripting():
50
        return get_num_channels_image_tensor(inpt)
51
52
53
54
55

    _log_api_usage_once(get_num_channels)

    kernel = _get_kernel(get_num_channels, type(inpt))
    return kernel(inpt)
56
57


58
@_register_kernel_internal(get_num_channels, torch.Tensor)
59
@_register_kernel_internal(get_num_channels, datapoints.Image, datapoint_wrapper=False)
60
61
62
63
64
65
66
67
68
69
70
def get_num_channels_image_tensor(image: torch.Tensor) -> int:
    chw = image.shape[-3:]
    ndims = len(chw)
    if ndims == 3:
        return chw[0]
    elif ndims == 2:
        return 1
    else:
        raise TypeError(f"Input tensor should have at least two dimensions, but got {ndims}")


71
get_num_channels_image_pil = _register_kernel_internal(get_num_channels, PIL.Image.Image)(_FP.get_image_num_channels)
72
73


74
@_register_kernel_internal(get_num_channels, datapoints.Video, datapoint_wrapper=False)
75
76
77
78
def get_num_channels_video(video: torch.Tensor) -> int:
    return get_num_channels_image_tensor(video)


79
80
81
82
83
# We changed the names to ensure it can be used not only for images but also videos. Thus, we just alias it without
# deprecating the old names.
get_image_num_channels = get_num_channels


84
def get_size(inpt: torch.Tensor) -> List[int]:
85
    if torch.jit.is_scripting():
86
        return get_size_image_tensor(inpt)
87
88
89
90
91

    _log_api_usage_once(get_size)

    kernel = _get_kernel(get_size, type(inpt))
    return kernel(inpt)
92
93


94
@_register_kernel_internal(get_size, torch.Tensor)
95
@_register_kernel_internal(get_size, datapoints.Image, datapoint_wrapper=False)
Philip Meier's avatar
Philip Meier committed
96
def get_size_image_tensor(image: torch.Tensor) -> List[int]:
97
98
99
100
101
102
    hw = list(image.shape[-2:])
    ndims = len(hw)
    if ndims == 2:
        return hw
    else:
        raise TypeError(f"Input tensor should have at least two dimensions, but got {ndims}")
103
104


105
@_register_kernel_internal(get_size, PIL.Image.Image)
Philip Meier's avatar
Philip Meier committed
106
def get_size_image_pil(image: PIL.Image.Image) -> List[int]:
107
108
109
110
    width, height = _FP.get_image_size(image)
    return [height, width]


111
@_register_kernel_internal(get_size, datapoints.Video, datapoint_wrapper=False)
Philip Meier's avatar
Philip Meier committed
112
113
def get_size_video(video: torch.Tensor) -> List[int]:
    return get_size_image_tensor(video)
114
115


116
@_register_kernel_internal(get_size, datapoints.Mask, datapoint_wrapper=False)
Philip Meier's avatar
Philip Meier committed
117
118
def get_size_mask(mask: torch.Tensor) -> List[int]:
    return get_size_image_tensor(mask)
119
120


121
@_register_kernel_internal(get_size, datapoints.BoundingBoxes, datapoint_wrapper=False)
Philip Meier's avatar
Philip Meier committed
122
123
def get_size_bounding_boxes(bounding_box: datapoints.BoundingBoxes) -> List[int]:
    return list(bounding_box.canvas_size)
124
125


126
@_register_unsupported_type(PIL.Image.Image, datapoints.Image, datapoints.BoundingBoxes, datapoints.Mask)
127
def get_num_frames(inpt: torch.Tensor) -> int:
128
    if torch.jit.is_scripting():
129
        return get_num_frames_video(inpt)
130
131
132
133
134

    _log_api_usage_once(get_num_frames)

    kernel = _get_kernel(get_num_frames, type(inpt))
    return kernel(inpt)
135
136


137
@_register_kernel_internal(get_num_frames, torch.Tensor)
138
139
140
@_register_kernel_internal(get_num_frames, datapoints.Video, datapoint_wrapper=False)
def get_num_frames_video(video: torch.Tensor) -> int:
    return video.shape[-4]
141
142


143
144
def _xywh_to_xyxy(xywh: torch.Tensor, inplace: bool) -> torch.Tensor:
    xyxy = xywh if inplace else xywh.clone()
145
146
147
148
    xyxy[..., 2:] += xyxy[..., :2]
    return xyxy


149
150
def _xyxy_to_xywh(xyxy: torch.Tensor, inplace: bool) -> torch.Tensor:
    xywh = xyxy if inplace else xyxy.clone()
151
152
153
154
    xywh[..., 2:] -= xywh[..., :2]
    return xywh


155
156
157
def _cxcywh_to_xyxy(cxcywh: torch.Tensor, inplace: bool) -> torch.Tensor:
    if not inplace:
        cxcywh = cxcywh.clone()
158

159
160
161
162
163
164
165
    # Trick to do fast division by 2 and ceil, without casting. It produces the same result as
    # `torchvision.ops._box_convert._box_cxcywh_to_xyxy`.
    half_wh = cxcywh[..., 2:].div(-2, rounding_mode=None if cxcywh.is_floating_point() else "floor").abs_()
    # (cx - width / 2) = x1, same for y1
    cxcywh[..., :2].sub_(half_wh)
    # (x1 + width) = x2, same for y2
    cxcywh[..., 2:].add_(cxcywh[..., :2])
166

167
168
169
170
171
172
173
174
175
176
177
178
179
    return cxcywh


def _xyxy_to_cxcywh(xyxy: torch.Tensor, inplace: bool) -> torch.Tensor:
    if not inplace:
        xyxy = xyxy.clone()

    # (x2 - x1) = width, same for height
    xyxy[..., 2:].sub_(xyxy[..., :2])
    # (x1 * 2 + width) / 2 = x1 + width / 2 = x1 + (x2-x1)/2 = (x1 + x2)/2 = cx, same for cy
    xyxy[..., :2].mul_(2).add_(xyxy[..., 2:]).div_(2, rounding_mode=None if xyxy.is_floating_point() else "floor")

    return xyxy
180
181


182
183
def _convert_format_bounding_boxes(
    bounding_boxes: torch.Tensor, old_format: BoundingBoxFormat, new_format: BoundingBoxFormat, inplace: bool = False
184
) -> torch.Tensor:
185

186
    if new_format == old_format:
187
        return bounding_boxes
188

189
    # TODO: Add _xywh_to_cxcywh and _cxcywh_to_xywh to improve performance
190
    if old_format == BoundingBoxFormat.XYWH:
191
        bounding_boxes = _xywh_to_xyxy(bounding_boxes, inplace)
192
    elif old_format == BoundingBoxFormat.CXCYWH:
193
        bounding_boxes = _cxcywh_to_xyxy(bounding_boxes, inplace)
194
195

    if new_format == BoundingBoxFormat.XYWH:
196
        bounding_boxes = _xyxy_to_xywh(bounding_boxes, inplace)
197
    elif new_format == BoundingBoxFormat.CXCYWH:
198
        bounding_boxes = _xyxy_to_cxcywh(bounding_boxes, inplace)
199

200
    return bounding_boxes
201
202


203
def convert_format_bounding_boxes(
204
    inpt: torch.Tensor,
205
206
207
    old_format: Optional[BoundingBoxFormat] = None,
    new_format: Optional[BoundingBoxFormat] = None,
    inplace: bool = False,
208
) -> torch.Tensor:
209
    # This being a kernel / dispatcher hybrid, we need an option to pass `old_format` explicitly for simple tensor
210
    # inputs as well as extract it from `datapoints.BoundingBoxes` inputs. However, putting a default value on
211
212
213
    # `old_format` means we also need to put one on `new_format` to have syntactically correct Python. Here we mimic the
    # default error that would be thrown if `new_format` had no default value.
    if new_format is None:
214
        raise TypeError("convert_format_bounding_boxes() missing 1 required argument: 'new_format'")
215
216

    if not torch.jit.is_scripting():
217
        _log_api_usage_once(convert_format_bounding_boxes)
218
219
220
221

    if torch.jit.is_scripting() or is_simple_tensor(inpt):
        if old_format is None:
            raise ValueError("For simple tensor inputs, `old_format` has to be passed.")
222
223
        return _convert_format_bounding_boxes(inpt, old_format=old_format, new_format=new_format, inplace=inplace)
    elif isinstance(inpt, datapoints.BoundingBoxes):
224
225
        if old_format is not None:
            raise ValueError("For bounding box datapoint inputs, `old_format` must not be passed.")
226
        output = _convert_format_bounding_boxes(
227
228
            inpt.as_subclass(torch.Tensor), old_format=inpt.format, new_format=new_format, inplace=inplace
        )
229
        return datapoints.BoundingBoxes.wrap_like(inpt, output, format=new_format)
230
231
232
233
234
235
    else:
        raise TypeError(
            f"Input can either be a plain tensor or a bounding box datapoint, but got {type(inpt)} instead."
        )


236
def _clamp_bounding_boxes(
Philip Meier's avatar
Philip Meier committed
237
    bounding_boxes: torch.Tensor, format: BoundingBoxFormat, canvas_size: Tuple[int, int]
238
) -> torch.Tensor:
239
240
    # TODO: Investigate if it makes sense from a performance perspective to have an implementation for every
    #  BoundingBoxFormat instead of converting back and forth
241
242
243
244
    in_dtype = bounding_boxes.dtype
    bounding_boxes = bounding_boxes.clone() if bounding_boxes.is_floating_point() else bounding_boxes.float()
    xyxy_boxes = convert_format_bounding_boxes(
        bounding_boxes, old_format=format, new_format=datapoints.BoundingBoxFormat.XYXY, inplace=True
245
    )
Philip Meier's avatar
Philip Meier committed
246
247
    xyxy_boxes[..., 0::2].clamp_(min=0, max=canvas_size[1])
    xyxy_boxes[..., 1::2].clamp_(min=0, max=canvas_size[0])
248
    out_boxes = convert_format_bounding_boxes(
249
250
251
        xyxy_boxes, old_format=BoundingBoxFormat.XYXY, new_format=format, inplace=True
    )
    return out_boxes.to(in_dtype)
252
253


254
def clamp_bounding_boxes(
255
    inpt: torch.Tensor,
256
    format: Optional[BoundingBoxFormat] = None,
Philip Meier's avatar
Philip Meier committed
257
    canvas_size: Optional[Tuple[int, int]] = None,
258
) -> torch.Tensor:
259
    if not torch.jit.is_scripting():
260
        _log_api_usage_once(clamp_bounding_boxes)
261
262

    if torch.jit.is_scripting() or is_simple_tensor(inpt):
Philip Meier's avatar
Philip Meier committed
263
264
265
266

        if format is None or canvas_size is None:
            raise ValueError("For simple tensor inputs, `format` and `canvas_size` has to be passed.")
        return _clamp_bounding_boxes(inpt, format=format, canvas_size=canvas_size)
267
    elif isinstance(inpt, datapoints.BoundingBoxes):
Philip Meier's avatar
Philip Meier committed
268
269
270
        if format is not None or canvas_size is not None:
            raise ValueError("For bounding box datapoint inputs, `format` and `canvas_size` must not be passed.")
        output = _clamp_bounding_boxes(inpt.as_subclass(torch.Tensor), format=inpt.format, canvas_size=inpt.canvas_size)
271
        return datapoints.BoundingBoxes.wrap_like(inpt, output)
272
273
274
275
    else:
        raise TypeError(
            f"Input can either be a plain tensor or a bounding box datapoint, but got {type(inpt)} instead."
        )