Skip to content
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

Add rotated bounding box formats #8841

Merged
merged 10 commits into from
Feb 20, 2025

Conversation

AntoineSimoulin
Copy link
Contributor

@AntoineSimoulin AntoineSimoulin commented Jan 8, 2025

This PR is part of a series of contributions aiming to add rotated boxes to torchvision. This first contribution aims at modifying the definition of bounding boxes in torchvision. We operate the two following modifications:

Extend BoundingBoxFormat for rotated boxes

We add four multiple allowed formats in BoundingBoxFormat. The formats "xyxyr", "xywhr", "cxcywhr" simply extend the non-rotated counterparts by adding a 5th coordinate to the bounding box, r, the rotation angle with respect to the box center by |r| degrees counter clock wise in the image plan. The last format "xyxyxyxy" represents a box with 4 corners.

Potential limitations:

  • We are proposing to extend BoundingBoxes instead of creating a new RoratedBoundingBoxes class. The reason is to simplify the possible input types for transforms and avoid having two different paths for transformations. For instance keeping a single horizontal_flip_bounding_boxes and _horizontal_flip_bounding_boxes_dispatch instead of creating a new function horizontal_flip_rotated_bounding_boxes;
  • This choice can have some disadvantages as some utility functions expect a 4-dimensional tensor and will be by design incompatible with rotated boxes. One example among other will be the generalized_box_iou_loss. However, please note these functions do not expect a BoundingBox as input, but a torch.Tensor[N, 4] or torch.Tensor[4]. So there is no direct incompatibility.

Add conversion functions for rotated boxes

We add 10 pairwise conversion functions in "_box_convert.py" to allow converting rotated bounding boxes between all four new formats. We also modified the logic in box_convert to support all possible conversion directions.

Potential limitations:

  • We chose to keep the convention previously used in torchvision for which (x1, y1) refer to top left of the bounding box and (x2, y2) refer to the bottom right of the bounding box. However, with the "xyxyxyxy" format it means that when going through the corner of the box in the counter clock-wise direction, we have the following sequence 1, 3, 2, 4. It would maybe make more sense to rename the bottom right of the bounding box as (x3, y3).

Testing

Please run unit tests for the modifications with: pytest test/test_ops.py -vvv -k TestBoxConvert

Next steps

Next modifications will aim at updating transforms functions (e.g. horizontal_flip_bounding_boxes), and adding utility functions specific to rotated boxes (e.g. rotated_box_area, _rotated_box_inter_union, rotated_box_iou).

cc @vfdev-5

Test Plan:
Run unit tests: `pytest test/test_ops.py -vvv -k TestBoxConvert`
Copy link

pytorch-bot bot commented Jan 8, 2025

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/vision/8841

Note: Links to docs will display an error until the docs builds have been completed.

❌ 5 New Failures, 4 Pending

As of commit 4001973 with merge base f709766 (image):

NEW FAILURES - The following jobs have failed:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

Copy link
Member

@NicolasHug NicolasHug left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks a lot for the PR @AntoineSimoulin ! I made some small comments below, I have higher-level points to discuss, let's sync! :)

@@ -17,15 +17,25 @@ class BoundingBoxFormat(Enum):
* ``XYXY``
* ``XYWH``
* ``CXCYWH``
* ``XYXYR``: rotated boxes represented via corners, x1, y1 being top left and x2, y2 being bottom right. r is rotation angle in degrees.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just to make it more explicit

Suggested change
* ``XYXYR``: rotated boxes represented via corners, x1, y1 being top left and x2, y2 being bottom right. r is rotation angle in degrees.
* ``XYXYR``: rotated boxes represented via corners, x1, y1 being top left and x2, y2 being bottom right. r is rotation angle in degrees in [0, 360).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this case the rotation angle do not necessarily have to be in the [0, 360). The format would work for negative rotations angle or even angles beyond 360 degrees.

test/test_ops.py Outdated
@@ -1288,6 +1288,38 @@ def test_bbox_same(self):
assert_equal(ops.box_convert(box_tensor, in_fmt="xywh", out_fmt="xywh"), exp_xyxy)
assert_equal(ops.box_convert(box_tensor, in_fmt="cxcywh", out_fmt="cxcywh"), exp_xyxy)

def test_rotated_bbox_same(self):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this kind of check is already taken care of in

@pytest.mark.parametrize("format", list(tv_tensors.BoundingBoxFormat))
@pytest.mark.parametrize("inplace", [False, True])
def test_kernel_noop(self, format, inplace):
input = make_bounding_boxes(format=format).as_subclass(torch.Tensor)
input_version = input._version
output = F.convert_bounding_box_format(input, old_format=format, new_format=format, inplace=inplace)
assert output is input
assert output.data_ptr() == input.data_ptr()
assert output._version == input_version

test/test_ops.py Outdated

assert exp_xywhr.size() == torch.Size([6, 5])
box_xywhr = ops.box_convert(box_tensor, in_fmt="xyxyr", out_fmt="xywhr")
assert torch.allclose(box_xywhr, exp_xywhr)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use torch.testing.assert_close() instead of torch.allclose, as it's more robust and provides better messages.

That being said, could we use assert_equal() here, since we're expecting integer-valued tensors? Is it because of the r column?

AntoineSimoulin and others added 3 commits January 22, 2025 09:41
Co-authored-by: Nicolas Hug <contact@nicolas-hug.com>
Test Plan:
`pytest test/test_transforms_v2.py -vvv -k "TestConvertBoundingBoxFormat"`
Summary:
Remove `test_rotated_bbox_same` test
@AntoineSimoulin
Copy link
Contributor Author

Modifications

The following commits address the modifications discussed offline:

  • Removal of "xyxyr" Format: The "xyxyr" format has been removed due to its limited use and potential for confusion. Modifying the "r" coordinate while leaving others unchanged perform a rotation around the center but also alters the shape of the rotated box,
  • Rotated Boxes Format Conversion: The conversion for rotated boxes is now implemented in the "transforms" section of the codebase instead of the "ops" section. Currently, this implementation supports the "xywhr" and "cxcywhr" formats.
  • Test Modifications: Test sets have been updated to prevent failures during the implementation of "transform" functions for rotated boxes. The make_bounding_boxes function has been modified to generate random boxes in "xywhr" and "cxcywhr" formats.
  • Implementation of Requested Modifications: This PR should also includes the requested changes discussed above.

Testing

Please execute the following unit tests to verify the modifications:

pytest test/test_ops.py -vvv -k TestBoxConvert
pytest test/test_transforms_v2.py -vvv -k "TestConvertBoundingBoxFormat"

Notes

  • Currently, the box transform operations remain in the "ops" directory as some tests require to do the comparison with the transform functions under the "transforms" directory. In particular the function test_strings;
  • The "xyxyxyxy" format is not included as it cannot be performed in-place due to a change in input tensor dimensions;
  • Test parametrization now only includes functions for already implemented formats using the @pytest.mark.parametrize("format", SUPPORTED_BOX_FORMATS) decorator.

Summary:
Fix failing tests for `TestConvertBoundingBoxFormat::test_correctness` and `TestConvertBoundingBoxFormat::test_strings`

Test Plan:
```bash
pytest test/test_transforms_v2.py -vvv -k "TestConvertBoundingBoxFormat"
...
87 passed, 32 skipped, 6964 deselected in 1.59s
```

Please note that the following tests `test/test_transforms_v2.py::TestConvertBoundingBoxFormat::test_correctness` were failing for previous format "CXCYWH", "XYXY" and "XYWH" for specific generated boxes.

```python
old_format = tv_tensors.BoundingBoxFormat.CXCYWH
new_format = tv_tensors.BoundingBoxFormat.XYXY

dtype = torch.int64
fn_type = "functional"
device = torch.device("cpu")


# bounding_boxes = make_bounding_boxes(format=old_format, dtype=dtype, device=device)
bounding_boxes = tv_tensors.BoundingBoxes([[ 5,  6, 10, 13]], format=tv_tensors.BoundingBoxFormat.CXCYWH, canvas_size=(17, 11))

if fn_type == "functional":
    fn = functools.partial(F.convert_bounding_box_format, new_format=new_format)
else:
    fn = transforms.ConvertBoundingBoxFormat(format=new_format)

actual = fn(bounding_boxes)
expected = _reference_convert_bounding_box_format(bounding_boxes, new_format)

assert_equal(actual, expected)
```
Copy link
Member

@NicolasHug NicolasHug left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the great PR @AntoineSimoulin .

I made some comments below, the main one relates to exposing XYXYXYXY in the transforms. Other than that, this looks great.

The CI shows a bunch of failing tests, but they're unrelated to this PR (I need to fix those separately....). We'll only care about the transforms_v2.py and test_ops.py tests.

The lint failure is real though: try using pre-commit to fix the formatting (https://github.com/pytorch/vision/blob/main/CONTRIBUTING.md#pre-commit-hooks)

You should only need to pip install pre-commit and then run pre-commit run --all-files

Comment on lines +3519 to +3520
old_new_formats = list(itertools.permutations(SUPPORTED_BOX_FORMATS, 2))
old_new_formats += list(itertools.permutations(NEW_BOX_FORMATS, 2))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that eventually, we'll want this to become old_new_formats = list(itertools.permutations(SUPPORTED_BOX_FORMATS + NEW_BOX_FORMATS, 2))

i.e. we'll probably also want to enable the kinf of rotated format <--> non-rotated format conversions. But this can come later and for this PR, we can keep things as-is.

old_new_formats = list(itertools.permutations(iter(tv_tensors.BoundingBoxFormat), 2))
old_new_formats = list(itertools.permutations(SUPPORTED_BOX_FORMATS, 2))
old_new_formats += list(itertools.permutations(NEW_BOX_FORMATS, 2))
# old_new_formats = list(itertools.permutations(NEW_BOX_FORMATS, 2))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: remove this line

# In the future, this global variable will be replaced with `list(tv_tensors.BoundingBoxFormat)`
# to support all available formats.
SUPPORTED_BOX_FORMATS = [tv_tensors.BoundingBoxFormat[x] for x in ["XYXY", "XYWH", "CXCYWH"]]
NEW_BOX_FORMATS = [tv_tensors.BoundingBoxFormat[x] for x in ["XYWHR", "CXCYWHR"]] # XYXYR
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's try to add XYXYXYXY as well here (see my other comment)

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']
boxes (Tensor[N, K]): boxes which will be converted. K is the number of coordinates (4 for unrotated bounding boxes or 5 for rotated bounding boxes)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can be 8 too

Summary:
Run `pre-commit run --all-files` to fix linting issues
@AntoineSimoulin
Copy link
Contributor Author

Modifications

The following commits address the modifications discussed offline:

  • Add the "xyxyxyxy" format in the "transforms" section of the codebase;
  • Modify the conversion in the "transforms" section of the codebase so that the operations are done in float format and then converted back to original format for non float tensor (e.g. int) so that the transformation are consistent with what is done in the "ops" section;
  • Replace _box_cxcywhr_to_xyxyxyxy and _box_xyxyxyxy_to_cxcywhr with _box_xywhr_to_xyxyxyxy and _box_xyxyxyxy_to_xywhr functions. Indeed "xywhr" is an easier intermediate format to convert from and back "xyxyxyxy" and is already used as an intermediate format in _convert_bounding_box_format;
  • Modify make_bounding_boxes function to generate boxes in "xyxyxyxy" format;
  • Fix linting and format issues listed above.

Testing

Please execute the following unit tests to verify the modifications:

pytest test/test_ops.py -vvv -k TestBoxConvert
pytest test/test_transforms_v2.py -vvv -k "TestConvertBoundingBoxFormat"

Copy link
Member

@NicolasHug NicolasHug left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks a lot @AntoineSimoulin . I just have a minor comment below, but we can address that in a follow-up PR.

I'll merge this when the CI is green(ish)!

elif new_format == BoundingBoxFormat.CXCYWHR:
bounding_boxes = _xywhr_to_cxcywhr(bounding_boxes, inplace)
elif new_format == BoundingBoxFormat.XYXYXYXY:
bounding_boxes = _xywhr_to_xyxyxyxy(bounding_boxes, inplace)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that the existing conversion logic is such that converting a non-rotated format to a rotated format would effectively be a no-op (and vice-versa). For example:

from torchvision.tv_tensors import BoundingBoxes
from torchvision.transforms.v2 import functional as F

bboxes = BoundingBoxes(
    [[0, 0, 10, 10]],
    format="XYXY",
    canvas_size=(50, 50)
)

out = F.convert_bounding_box_format(bboxes, new_format="XYWHR")
print(out)

This gives

BoundingBoxes([[ 0,  0, 10, 10]], format=BoundingBoxFormat.XYWHR, canvas_size=(50, 50))

which is obviously wrong. I think we should just raise an error when converting non-rorated formats to rotated formats (and the other way around too).

Note that in box_convert, the main logic is slightly different, so this is handled natively.

@NicolasHug NicolasHug merged commit 501a2c9 into pytorch:main Feb 20, 2025
62 of 67 checks passed
Copy link

Hey @NicolasHug!

You merged this PR, but no labels were added.
The list of valid labels is available at https://github.com/pytorch/vision/blob/main/.github/process_commit.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants