def test_uint(dtype): data = np.arange(50, dtype=dtype) data_scaled = data * 256**(data.dtype.itemsize - 1) assert convert_to_uint8(data_scaled).dtype == np.uint8 assert np.all(data == convert_to_uint8(data_scaled)) assert np.all(img_as_ubyte(data) == convert_to_uint8(data)) assert np.all(img_as_ubyte(data_scaled) == convert_to_uint8(data_scaled))
def test_float(dtype): data = np.linspace(0, 0.5, 128, dtype=dtype, endpoint=False) res = np.arange(128, dtype=np.uint8) assert convert_to_uint8(data).dtype == np.uint8 assert np.all(convert_to_uint8(data) == res) data = np.linspace(0, 1, 256, dtype=dtype) res = np.arange(256, dtype=np.uint8) assert np.all(convert_to_uint8(data) == res) assert np.all(img_as_ubyte(data) == convert_to_uint8(data)) assert np.all(img_as_ubyte(data - 0.5) == convert_to_uint8(data - 0.5))
def make_thumbnail(image: np.ndarray, shape=(30, 30, 4)) -> np.ndarray: """Resizes an image to `shape` with padding""" from napari.layers.utils.layer_utils import convert_to_uint8 from scipy import ndimage as ndi scale_factor = np.min(np.divide(shape, image.shape)) intermediate_image = ndi.zoom(image, (scale_factor, scale_factor, 1)) padding_needed = np.subtract(shape, intermediate_image.shape) pad_amounts = [(p // 2, (p + 1) // 2) for p in padding_needed] thumbnail = np.pad(intermediate_image, pad_amounts, mode="constant") thumbnail = convert_to_uint8(thumbnail) # blend thumbnail with opaque black background background = np.zeros(shape, dtype=np.uint8) background[..., 3] = 255 f_dest = thumbnail[..., 3][..., None] / 255 f_source = 1 - f_dest thumbnail = thumbnail * f_dest + background * f_source return thumbnail.astype(np.uint8)
def test_bool(): data = np.zeros((10, 10), dtype=np.bool) data[2:-2, 2:-2] = 1 converted = convert_to_uint8(data) assert converted.dtype == np.uint8 assert np.all(img_as_ubyte(data) == converted)