import numpy as np


def condense(im_label):
    """
    Shifts labels in a label image to fill in gaps corresponding to missing
    values.

    Parameters
    ----------
    im_label : array_like
        A label image generated by segmentation methods.

    Returns
    -------
    Condensed : array_like
        A label image where all values > 0 are shifted down to fill gaps.

    See Also
    --------
    histomicstk.segmentation.label.shuffle

    """
    import scipy.ndimage as ndi

    # initialize output
    Condensed = im_label.copy()

    # get extent of each object
    Locations = ndi.find_objects(Condensed)

    # initialize counter
    Counter = 1

    # fill in new values
    for i in np.arange(1, len(Locations) + 1):
        if Locations[i - 1] is not None:
            Patch = Condensed[Locations[i - 1]]
            Patch[Patch == i] = Counter
            Counter += 1

    return Condensed
