import torch


def compute_bbox_proj(verts, f, img_size=256):
    """
    Computes the 2D bounding box of vertices projected to the image plane.

    Args:
        verts (B x N x 3): Vertices.
        f (float): Focal length.
        img_size (int): Size of image in pixels.

    Returns:
        Bounding box in xywh format (Bx4).
    """
    xy = verts[:, :, :2]
    z = verts[:, :, 2:]
    proj = f * xy / z + 0.5  # [0, 1]
    proj = proj * img_size  # [0, img_size]
    u, v = proj[:, :, 0], proj[:, :, 1]
    x1, x2 = u.min(1).values, u.max(1).values
    y1, y2 = v.min(1).values, v.max(1).values
    return torch.stack((x1, y1, x2 - x1, y2 - y1), 1)