from .coordinates import COCOCoordinates
from dataclasses import InitVar, dataclass, field
from typing import Optional
[docs]
@dataclass(slots=True, kw_only=True)
class BoundingBox:
"""
A class to represent a bounding box.
This class can be initialised with either COCO format bounding box coordinates,
or with XYXY format bounding box coordinates. Either way, the coordinates are then
stored internally in COCO format.
Attributes:
coords (COCOCoordinates): The bounding box coordinates in COCO format.
"""
# Properties
coords: COCOCoordinates = field(init=False)
image_height: Optional[int] = None
@property
def area(self) -> float:
"""
Calculate the area of the bounding box.
Returns:
float: The area of the bounding box.
"""
return float(self.coords.h) * float(self.coords.w)
# Init-only fields
input_coords: InitVar[list[int]]
def __post_init__(self, input_coords: list[int]):
x, y, w, h = input_coords
self.coords = COCOCoordinates(int(x), int(y), int(w), int(h), image_height=self.image_height)
def __str__(self):
return self.coords.__str__()