如何调整图像大小但保持 sk-image 中的像素值?

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

我想调整图片大小。我的图像包含特定值 [0、1、2、7、9]。调整大小后,会引入新值,例如 5 等等。我想阻止这种情况。

我目前正在使用 scikit 图片调整功能。我已经尝试了所有插值标志但无济于事。

编辑:显示问题的简单代码

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))

如果要避免引入新值,需要避免线性、双线性、二次和其他"calculated"类型的插值,使用NEAREST_NEIGHBOUR插值。这对于调色板(即索引)图像和 classification 图像尤其重要,其中每个数字代表一个 class,这可能意味着在 class 之间进行插值,表示 [=26] =] 和代表 "highway" 的相邻 class 突然在两者之间引入了一些新值,这意味着您已经在亚利桑那州建造了一个海滩!

也就是说,使用order=0(对应"nearest neighbour")而不是默认的order=1(对应 "bilinear") 调整大小时。

各种插值类型详解here.

您不需要抗锯齿,但调整大小功能会默认应用它,(因此该功能将在图像上应用高斯核以消除锯齿)所以如果您想保留原始像素,您必须通过 anti_aliasing=False

禁用此标志
resized_image = resize(image, (50, 50), preserve_range=True, anti_aliasing=False,order=0).astype('uint8')

通过此更改,输出将是:

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

通过查看调整大小函数文档,我们可以看到高斯核仅在调整后的图像小于原始图像时才适用。(这是你的情况)

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.

anti_aliasing设置为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.

混叠滤波器应用高斯滤波器,产生新值。


结果:

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