import torch


def box_corners_to_center(corners):
    """
    Arguments:
        corners (Tensor[N, 8]): boxes to be converted. They are
            expected to be in (x0, y0, ..., x3, y3) format, where the corners are sorted counterclockwise.
    Returns:
        b (Tensor[N, 6]): converted boxes in centered
            (x_c, y_c, w, h, c, s) format.
            * c, s: sin, cos before sigmoid
    """

    x0, y0, x1, y1, x2, y2, x3, y3 = corners.unbind(-1)

    x_c = (x0 + x2) / 2
    y_c = (y0 + y2) / 2

    wsin, wcos, hsin, hcos = (y1 - y0, x1 - x0, x0 + x1, y2 + y3)
    theta = torch.atan2(wsin, wcos)
    c = torch.cos(theta)
    s = torch.sin(theta)

    b = [x_c, y_c, (wsin ** 2 + wcos ** 2).sqrt(), (hsin ** 2 + hcos ** 2).sqrt(), c, s]
    return torch.stack(b, dim=-1)