import torch


def compute_bboxes_from_keypoints(keypoints):
    """
    keypoints: B x 68*2
    return value: B x 4 (t, b, l, r)
    Compute a very rough bounding box approximate from 68 keypoints.
    """
    x, y = keypoints.float().view(-1, 68, 2).transpose(0, 2)

    face_height = y[8] - y[27]
    b = y[8] + face_height * 0.2
    t = y[27] - face_height * 0.47

    midpoint_x = (x.min(dim=0)[0] + x.max(dim=0)[0]) / 2
    half_height = (b - t) * 0.5

    l = midpoint_x - half_height
    r = midpoint_x + half_height


    return torch.stack([t, b, l, r], dim=1)