def clip_rect_to_image(rect, img_width, img_height):
    """Ensure that the rectangle is within the image boundaries.
    Explicitly casts all entries to integer.
    :param rect: list/tuple (l,t,w,h)
    :param img_width: int
    :param img_height: int
    :return: (l, t, w, h)
    """
    l, t, w, h = int(rect[0]), int(rect[1]), int(rect[2]), int(rect[3])
    # Right/bottom bounds are exclusive
    r = max(0, min(img_width, l+w))
    b = max(0, min(img_height, t+h))
    # Left/top bounds are inclusive
    l = max(0, l)
    t = max(0, t)
    return (l, t, r-l, b-t)