util.py 文件源码

python
阅读 19 收藏 0 点赞 0 评论 0

项目:radar 作者: amoose136 项目源码 文件源码
def image_as_uint8(im):
    """ Convert the given image to uint8

    If the dtype is already uint8, it is returned as-is. If the image
    is float, and all values are between 0 and 1, the values are
    multiplied by 255. In all other situations, the values are scaled
    such that the minimum value becomes 0 and the maximum value becomes
    255.
    """
    if not isinstance(im, np.ndarray):
        raise ValueError('image must be a numpy array')
    dtype_str = str(im.dtype)
    # Already uint8?
    if dtype_str == 'uint8':
        return im
    # Handle float
    mi, ma = np.nanmin(im), np.nanmax(im)
    if dtype_str.startswith('float'):
        if mi >= 0 and ma <= 1:
            mi, ma = 0, 1
    # Now make float copy before we scale
    im = im.astype('float32')
    # Scale the values between 0 and 255
    if np.isfinite(mi) and np.isfinite(ma):
        if mi:
            im -= mi
        if ma != 255:
            im *= 255.0 / (ma - mi)
        assert np.nanmax(im) < 256
    return im.astype(np.uint8)


# currently not used ... the only use it to easly provide the global meta info
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号