Repository: scikit-image/scikit-image

Issue:
rescale and other warp functions should preserve input range and dtype
## Description

See this StackOverflow question for the motivation:

https://stackoverflow.com/questions/66585291/skimage-rescale-segmentation-mask

For higher-order interpolation, we need to do floating point arithmetic so it makes sense to convert to float and change the intensity scale as per our data type rules. For order=0, though, I think it makes most sense to preserve the input dtype and range.

```python
In [1]: import numpy as np
In [2]: from skimage import transform
In [3]: seg_mask = np.random.randint(0, 2**16, size=(16, 16)).astype(np.uint16)
In [4]: transform.rescale(seg_mask, 0.5, order=0)
Out[4]:
array([[0.5222858 , 0.55330739, 0.76211185, 0.61666285, 0.45897612,
        0.19795529, 0.52283513, 0.56203555],
       [0.57460899, 0.81582361, 0.61560998, 0.68281071, 0.3169604 ,
        0.19830625, 0.40459297, 0.48615244],
       [0.47759213, 0.62240024, 0.76609445, 0.333196  , 0.88154421,
        0.43877317, 0.50019074, 0.65618372],
       [0.84681468, 0.58448157, 0.56137942, 0.2824445 , 0.76746777,
        0.75156786, 0.47310597, 0.66036469],
       [0.18850996, 0.60334173, 0.25194171, 0.83747616, 0.56156252,
        0.61664759, 0.80070192, 0.48683909],
       [0.29718471, 0.3195697 , 0.32796216, 0.58196384, 0.81673915,
        0.50057221, 0.48458076, 0.27048142],
       [0.52285039, 0.35194934, 0.84243534, 0.68207828, 0.66150912,
        0.46347753, 0.23147936, 0.84484627],
       [0.51114672, 0.35536736, 0.87023728, 0.44734874, 0.6835584 ,
        0.54543374, 0.43472953, 0.78928817]])

In [5]: transform.rescale(seg_mask, 0.5, order=0, preserve_range=True)
Out[5]:
array([[34228., 36261., 49945., 40413., 30079., 12973., 34264., 36833.],
       [37657., 53465., 40344., 44748., 20772., 12996., 26515., 31860.],
       [31299., 40789., 50206., 21836., 57772., 28755., 32780., 43003.],
       [55496., 38304., 36790., 18510., 50296., 49254., 31005., 43277.],
       [12354., 39540., 16511., 54884., 36802., 40412., 52474., 31905.],
       [19476., 20943., 21493., 38139., 53525., 32805., 31757., 17726.],
       [34265., 23065., 55209., 44700., 43352., 30374., 15170., 55367.],
       [33498., 23289., 57031., 29317., 44797., 35745., 28490., 51726.]])
```

## Way to reproduce
```python
import numpy as np
from skimage import transform
seg_mask = np.random.randint(0, 2**16, size=(16, 16)).astype(np.uint16)
print(transform.rescale(seg_mask, 0.5, order=0))
print(transform.rescale(seg_mask, 0.5, order=0, preserve_range=True))
```



Discussion:

Resolving patch:
diff --git a/skimage/transform/_warps.py b/skimage/transform/_warps.py
--- a/skimage/transform/_warps.py
+++ b/skimage/transform/_warps.py
@@ -139,7 +139,8 @@ def resize(image, output_shape, order=None, mode='reflect', cval=0, clip=True,
         # The grid_mode kwarg was introduced in SciPy 1.6.0
         order = _validate_interpolation_order(image.dtype, order)
         zoom_factors = [1 / f for f in factors]
-        image = convert_to_float(image, preserve_range)
+        if order > 0:
+            image = convert_to_float(image, preserve_range)
         out = ndi.zoom(image, zoom_factors, order=order, mode=ndi_mode,
                        cval=cval, grid_mode=True)
         _clip_warp_output(image, out, order, mode, cval, clip)
@@ -827,7 +828,8 @@ def warp(image, inverse_map, map_args={}, output_shape=None, order=None,
 
     order = _validate_interpolation_order(image.dtype, order)
 
-    image = convert_to_float(image, preserve_range)
+    if order > 0:
+        image = convert_to_float(image, preserve_range)
 
     input_shape = np.array(image.shape)
 
@@ -849,7 +851,7 @@ def warp(image, inverse_map, map_args={}, output_shape=None, order=None,
              "skimage's implementation is fixed, we recommend "
              "to use bi-linear or bi-cubic interpolation instead.")
 
-    if order in (0, 1, 3) and not map_args:
+    if order in (1, 3) and not map_args:
         # use fast Cython version for specific interpolation orders and input
 
         matrix = None


Test patch:
diff --git a/skimage/transform/tests/test_warps.py b/skimage/transform/tests/test_warps.py
--- a/skimage/transform/tests/test_warps.py
+++ b/skimage/transform/tests/test_warps.py
@@ -1,8 +1,9 @@
+import pytest
 import numpy as np
 from scipy.ndimage import map_coordinates
 
 from skimage.data import checkerboard, astronaut
-from skimage.util.dtype import img_as_float
+from skimage.util.dtype import img_as_float, _convert
 from skimage.color.colorconv import rgb2gray
 from skimage.draw.draw import circle_perimeter_aa
 from skimage.feature.peak import peak_local_max
@@ -160,7 +161,8 @@ def test_rotate_resize_center():
     ref_x45[6, 0] = 1
     ref_x45[7, 0] = 1
 
-    x45 = rotate(x, 45, resize=True, center=(3, 3), order=0)
+    x45 = rotate(x, 45, resize=True, center=(3, 3), order=0,
+                 mode='reflect')
     # new dimension should be d = sqrt(2 * (10/2)^2)
     assert x45.shape == (14, 14)
     assert_equal(x45, ref_x45)
@@ -349,8 +351,8 @@ def test_resize_dtype():
     assert resize(x, (10, 10), preserve_range=True).dtype == x.dtype
     assert resize(x_u8, (10, 10), preserve_range=False).dtype == np.double
     assert resize(x_u8, (10, 10), preserve_range=True).dtype == np.double
-    assert resize(x_b, (10, 10), preserve_range=False).dtype == np.double
-    assert resize(x_b, (10, 10), preserve_range=True).dtype == np.double
+    assert resize(x_b, (10, 10), preserve_range=False).dtype == bool
+    assert resize(x_b, (10, 10), preserve_range=True).dtype == bool
     assert resize(x_f32, (10, 10), preserve_range=False).dtype == x_f32.dtype
     assert resize(x_f32, (10, 10), preserve_range=True).dtype == x_f32.dtype
 
@@ -535,7 +537,7 @@ def test_keep_range():
                   mode='constant', multichannel=False, anti_aliasing=False,
                   clip=True, order=0)
     assert out.min() == 0
-    assert out.max() == 2 / 255.0
+    assert out.max() == 2
 
 
 def test_zero_image_size():
@@ -684,3 +686,15 @@ def test_boll_array_warnings():
 
     with expected_warnings(['Input image dtype is bool']):
         warp(img, np.eye(3), order=1)
+
+
+@pytest.mark.parametrize('dtype', [np.uint8, bool, np.float32, np.float64])
+def test_order_0_warp_dtype(dtype):
+
+    img = _convert(astronaut()[:10, :10, 0], dtype)
+
+    assert resize(img, (12, 12), order=0).dtype == dtype
+    assert rescale(img, 0.5, order=0).dtype == dtype
+    assert rotate(img, 45, order=0).dtype == dtype
+    assert warp_polar(img, order=0).dtype == dtype
+    assert swirl(img, order=0).dtype == dtype