Search code examples
pythonscipyresizescikit-image

How to resize an image but maintain pixel values in sk-image?


I want to resize images. My images contain specific values [0, 1, 2, 7, 9]. After resizing, new values are introduced like 5 and whatnot. I want to prevent that.

I'm currently using scikit image resize function. I've tried all interpolation flags but to no avail.

EDIT: a simple code to show the problem

import numpy as np
from skimage.transform import resize
vals = [0, 1, 4, 6]
N, M = 100, 100
image = np.random.choice(vals, N * M).reshape(N, M).astype('uint8')
resized_image = resize(image, (50, 50), preserve_range=True).astype('uint8')

print('vals before resizing ', np.unique(image))
print('vals after resizing ', np.unique(resized_image))

Solution

  • Set anti_aliasing to False:

    resized_image = resize(image, (50, 50), order=0, preserve_range=True, anti_aliasing=False).astype('uint8')
    

    anti_aliasingbool, optional
    Whether to apply a Gaussian filter to smooth the image prior to down-scaling. It is crucial to filter when down-sampling the image to avoid aliasing artifacts.

    The aliasing filter applies Gaussian filter, that produces new values.


    Result:

    vals before resizing  [0 1 4 6]
    vals after resizing  [0 1 4 6]