Skip to content

box_rescale function to rescale bounding boxes to a new image shape #3980

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/source/ops.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ torchvision.ops
.. autofunction:: batched_nms
.. autofunction:: remove_small_boxes
.. autofunction:: clip_boxes_to_image
.. autofunction:: box_rescale
.. autofunction:: box_convert
.. autofunction:: box_area
.. autofunction:: box_iou
Expand Down
18 changes: 18 additions & 0 deletions torchvision/ops/boxes.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,24 @@ def clip_boxes_to_image(boxes: Tensor, size: Tuple[int, int]) -> Tensor:
return clipped_boxes.reshape(boxes.shape)


def box_rescale(boxes: Tensor, in_shape: Tuple[int, int], out_shape: Tuple[int, int]) -> Tensor:
"""
Rescale boxes to a new image shape.

Args:
boxes: (Tensor[N, 4]): boxes to rescale, in ``(x1, y1, x2, y2)`` format.
in_shape: (Tuple[int, int]): current shape of the image.
out_shape: (Tuple[int, int]): desired shape of the image.

Returns:
Tensor[N, 4]: rescaled boxes
"""
rescaled = boxes.new(boxes.shape)
rescaled[:, 0::2] = boxes[:, 0::2] * (out_shape[1] / in_shape[1])
rescaled[:, 1::2] = boxes[:, 1::2] * (out_shape[0] / in_shape[0])
return rescaled


def box_convert(boxes: Tensor, in_fmt: str, out_fmt: str) -> Tensor:
"""
Converts boxes from given in_fmt to out_fmt.
Expand Down