When resizing images in computer vision applications, bounding box coordinates must be scaled proportionally to maintain accurate object detection.
import cv2
import numpy as np
from ultralytics.utils.ops import scale_boxes
# Load the original image
original_image = cv2.imread("sample_images/vehicle.jpg")
original_height, original_width, channels = original_image.shape
# Resize the image by scaling factors
scaled_image = cv2.resize(original_image, None, fx=1.5, fy=1.5)
new_height, new_width, _ = scaled_image.shape
# Define bounding boxes in original image coordinates
detection_boxes = np.array(
[
[15.234, 180.456, 650.789, 623.123],
[32.345, 320.123, 180.456, 745.678],
[520.123, 310.987, 650.789, 710.234],
[145.678, 330.123, 280.123, 690.456],
[0, 420.123, 45.678, 690.123],
[0.034, 195.345, 25.678, 267.890]
]
)
# Scale the bounding boxes to match the resized image
adjusted_boxes = scale_boxes(
img1_shape=(original_height, original_width), # original dimensions
boxes=detection_boxes, # original bounding boxes
img0_shape=(new_height, new_width), # new image dimensions
ratio_pad=None,
padding=False,
xywh=False
)
print("Adjusted bounding boxes:", adjusted_boxes)
Coordinate System Transformation
Converting between different bounding box coordinate formats is essential for various computer vision tasks and model outputs.
XYXY to XYWH Convesrion
Transform bounding boxes from (x1, y1, x2, y2) format to (x_center, y_center, width, height) representation.
import numpy as np
from ultralytics.utils.ops import xyxy2xywh
# Define bounding boxes in corner coordinates format
corner_boxes = np.array(
[
[15.234, 180.456, 650.789, 623.123],
[32.345, 320.123, 180.456, 745.678],
[520.123, 310.987, 650.789, 710.234],
[145.678, 330.123, 280.123, 690.456],
[0, 420.123, 45.678, 690.123],
[0.034, 195.345, 25.678, 267.890]
]
)
# Convert to center-point format
center_boxes = xyxy2xywh(corner_boxes)
print("Converted boxes:", center_boxes)
Available Coordinate Transformations
The Ultralytics library provides comprehensive functions for converting between various bounding box formats:
from ultralytics.utils.ops import (
ltwh2xywh,
ltwh2xyxy,
xywh2ltwh,
xywh2xyxy,
xywhn2xyxy,
xyxy2ltwh,
xyxy2xywhn
)
# Example usage of different conversion functions
sample_box = np.array([100, 150, 200, 250]) # x1, y1, x2, y2
# Convert to different formats
xywh_format = xyxy2xywh(sample_box)
ltwh_format = xyxy2ltwh(sample_box)
normalized_format = xyxy2xywhn(sample_box)
print("XYWH format:", xywh_format)
print("LTWH format:", ltwh_format)
print("Normalized format:", normalized_format)