def batched_mask_to_box(masks: paddle.Tensor) -> paddle.Tensor:
    """
    Calculates boxes in XYXY format around masks. Return [0,0,0,0] for
    an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4.
    """
    # paddle.max below raises an error on empty inputs, just skip in this case
    if paddle.numel(masks) == 0:
        return paddle.zeros([*masks.shape[:-2], 4])

    # Normalize shape to CxHxW
    shape = masks.shape
    h, w = shape[-2:]
    if len(shape) > 2:
        masks = masks.flatten(0, -3)
    else:
        masks = masks.unsqueeze(0)

    # Get top and bottom edges
    in_height = paddle.max(masks, axis=-1)
    in_height_coords = in_height * paddle.arange(end=h)[None, :]
    bottom_edges = paddle.max(in_height_coords, axis=-1)
    #import pdb;pdb.set_trace()
    in_height_coords = in_height_coords + h * (1 - in_height)
    #in_height_coords = in_height_coords + w * ((~(in_height.cast('bool')).astype('uint8')+2).astype('bool').cast('int32'))
    top_edges = paddle.min(in_height_coords, axis=-1)

    # Get left and right edges
    in_width = paddle.max(masks, axis=-2)
    in_width_coords = in_width * paddle.arange(end=w)[None, :]
    right_edges = paddle.max(in_width_coords, axis=-1)
    #in_width_coords = in_width_coords + w * ((~(in_width.cast('bool')).astype('uint8')+2).astype('bool').cast('int32'))
    in_width_coords = in_width_coords + w * (1 - in_width)
    left_edges = paddle.min(in_width_coords, axis=-1)

    # If the mask is empty the right edge will be to the left of the left edge.
    # Replace these boxes with [0, 0, 0, 0]
    empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges)
    out = paddle.stack(
        [left_edges, top_edges, right_edges, bottom_edges], axis=-1)
    out = out * (~empty_filter).unsqueeze(-1)

    # Return to original shape
    if len(shape) > 2:
        out = out.reshape([*shape[:-2], 4])
    else:
        out = out[0]

    return out

    Calculates boxes in XYXY format around masks. Return [0,0,0,0] for
    an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4.
    
contrib/SegmentAnything/segment_anything/utils/amg.py