import torch


def xyxy2xywh(xyxy):
    """Convert bounding box enconding from [x1, y1, x2, y2] to [x, y, w, h]."""
    # the input tensor must have four components in the last dimension
    xywh = torch.zeros_like(xyxy)
    xywh[:, 0] = (xyxy[:, 0] + xyxy[:, 2]) / 2
    xywh[:, 1] = (xyxy[:, 1] + xyxy[:, 3]) / 2
    xywh[:, 2] = xyxy[:, 2] - xyxy[:, 0]
    xywh[:, 3] = xyxy[:, 3] - xyxy[:, 1]
    return xywh