def threshold_image(img, bkground_thresh, bkground_value=0.0):
    """
    Thresholds a given image at a value or percentile.

    Replacement value can be specified too.


    Parameters
    -----------
    image_in : ndarray
        Input image

    bkground_thresh : float
        a threshold value to identify the background

    bkground_value : float
        a value to fill the background elements with. Default 0.

    Returns
    -------

    thresholded_image : ndarray
        thresholded and/or filled image

    """

    if bkground_thresh is None:
        return img

    if isinstance(bkground_thresh, str):
        try:
            thresh_perc = float(bkground_thresh.replace('%', ''))
        except:
            raise ValueError(
                'percentile specified could not be parsed correctly '
                ' - must be a string of the form "5%", "10%" etc')
        else:
            thresh_value = np.percentile(img, thresh_perc)
    elif isinstance(bkground_thresh, (float, int)):
        thresh_value = bkground_thresh
    else:
        raise ValueError('Invalid specification for background threshold.')

    img[img < thresh_value] = bkground_value

    return img