import warnings


def foregroundPixels(image, foreground_labels, image_transform=None, background_class_index=None):
    """ Extract foreground pixels from an image.

    Parameters
    ----------
    image : numpy array, shape (img_height, img_width, num_channels)
        Image the foreground pixels will be extracted from.
    foreground_labels : numpy array of bool or int, shape (img_height, img_width)
        Pixel-level label image. See argument `background_class_index`.
    image_transform : funtion, optional
        If provided, this function is applied to `image` before extracting
        foreground pixels.
    background_class_index : int, optional
        If this argument is `None`, `foreground_labels` is treated as a boolean
        array whose (i, j)-th element is True if the (i, j)-th pixel of `image`
        is in the foreground, and False if it is in the background.
        If this argument is an integer, `foreground_labels` is treated as an
        array of class labels. This can be convenient if you have a label image
        that assigns labels >= 1 to foreground and 0 to background, for example.
        Default is None.

    Returns
    -------
    foreground_pixels : numpy array, shape (num_foreground_pixels, num_channels)
        The foreground pixels in `image`, as identified by `foreground_labels`.
        If a value was passed for `image_transform`, the number of columns in
        the output could be different from `num_channels`.

    See Also
    --------
    features.imageFromForegroundPixels
    """

    if background_class_index is None:
        is_foreground = foreground_labels
    else:
        is_foreground = ~(foreground_labels == background_class_index)

    if image_transform is not None:
        # Colorspace conversion transforms can throw a divide-by-zero warning
        # for images with zero-valued pixels, but we don't want to see them.
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", "divide by zero")
            image = image_transform(image)

    foreground_pixels = image[is_foreground]
    return foreground_pixels