Find a threshold where the fraction of pixels above the threshold
    is closest to density where density is (count of pixels above
    threshold / count of pixels).

    The highest threshold closest to the desired density will be returned.

    Use low and high to exclude undesirable thresholds.

    :param img: target image
    :type img: 2d :class:`numpy.ndarray`
    :param density: target density
    :type density: float between 0.0 and 1.0
    :param low: min threshold to test
    :type low: ubyte
    :param migh: max threshold to test
    :type low: ubyte
    :rtype: ubyte

def find_threshold_near_density(img, density, low=0, high=255):
    """Find a threshold where the fraction of pixels above the threshold
    is closest to density where density is (count of pixels above
    threshold / count of pixels).

    The highest threshold closest to the desired density will be returned.

    Use low and high to exclude undesirable thresholds.

    :param img: target image
    :type img: 2d :class:`numpy.ndarray`
    :param density: target density
    :type density: float between 0.0 and 1.0
    :param low: min threshold to test
    :type low: ubyte
    :param migh: max threshold to test
    :type low: ubyte
    :rtype: ubyte

    """
    size = numpy.size(img)
    densities = []
    last_t = None
    while True:
        t = ((high - low) // 2) + low
        if t == last_t:
            densities.sort(key=lambda x: (abs(x[0] - density), 256 - x[1]))
            return densities[0][1]
        else:
            last_t = t
        d = numpy.count_nonzero(img > t) / size
        densities.append((d, t))
        if d < density:
            high = t
        elif d >= density:  # search away from low
            low = t