import numpy as np

from .condense import condense


def area_open(im_label, min_area):
    """Removes small objects from label image.

    Parameters
    ----------
    im_label : array_like
        A uint32 type label image generated by segmentation methods.
    min_area : int
        minimum area threshold for objects. Objects with fewer than 'min_area'
        pixels will be zeroed to merge with background.

    Returns
    -------
    im_open : array_like
        A uint32 label where objects with pixels < min_area are removed.

    Notes
    -----
    Objects are assumed to have positive nonzero values. im_label image will be
    condensed during processing.

    See Also
    --------
    histomicstk.segmentation.label.condense,
    histomicstk.segmentation.label.shuffle,
    histomicstk.segmentation.label.split,
    histomicstk.segmentation.label.width_open

    """
    import scipy.ndimage as ndi

    # copy input image
    im_open = im_label.copy()

    # condense label image
    if np.unique(im_open).size - 1 != im_open.max():
        im_open = condense(im_open)

    # count pixels in each object
    Counts, Edges = np.histogram(im_open, bins=im_open.max() + 1)

    # get locations of objects in initial image
    Locations = ndi.find_objects(im_open)

    # iterate through objects, zeroing where needed
    for i in np.arange(1, Counts.size):
        if Counts[i] < min_area:

            # extract object from label image
            Template = im_open[Locations[i - 1]]

            # label mask of object 'i'
            Template[Template == i] = 0

    # condense to fill gaps
    im_open = condense(im_open)

    return im_open
