import torch


def clip_boxes_to_image(boxes, size):
    """copy from torchvision.ops.boxes

    Clip boxes so that they lie inside an image of size `size`.

    Arguments:
        boxes (Tensor[N, 4]): (left, top, right, bottom)
        size (Tuple(H, W)): size of the image

    Returns:
        clipped_boxes (Tensor[N, 4])
    """
    dim = boxes.dim()
    boxes_x = boxes[..., 0::2]
    boxes_y = boxes[..., 1::2]
    height, width = size
    boxes_x = boxes_x.clamp(min=0, max=width - 1)
    boxes_y = boxes_y.clamp(min=0, max=height - 1)
    clipped_boxes = torch.stack((boxes_x, boxes_y), dim=dim)
    return clipped_boxes.reshape(boxes.shape)