使用 scipy 和 PIL 调整最近邻图像大小错误

Nearest neighbor image resizing wrong using scipy and PIL

我正在尝试拍摄一张小图像并使用 Python 制作它的大 ("pixelated") 版本。我已经尝试在 scipyPIL.Image 中使用最近邻大小调整方法,但都输出相同的错误结果。这是一个尝试将图像上采样 3 倍的示例:

import numpy as np
from scipy.misc import imresize
from PIL import Image

img = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.uint8)
img_nn_scipy = imresize(img, (9, 9), interp='nearest')
img_nn_pil   = np.array(Image.fromarray(img).resize((9, 9), Image.NEAREST))

print img_nn_scipy
print img_nn_pil

两个打印语句输出相同的结果:

[[1 1 1 2 2 2 2 3 3]
 [1 1 1 2 2 2 2 3 3]
 [1 1 1 2 2 2 2 3 3]
 [4 4 4 5 5 5 5 6 6]
 [4 4 4 5 5 5 5 6 6]
 [4 4 4 5 5 5 5 6 6]
 [4 4 4 5 5 5 5 6 6]
 [7 7 7 8 8 8 8 9 9]
 [7 7 7 8 8 8 8 9 9]]

我预计原始图像中的每个数字现在都将替换为一个 3x3 块,所有块都包含相同的值。相反,块具有不同的大小,只有 1 块是 3x3。

这有什么原因吗? Python有没有办法合理解决这个问题?

谢谢!

尝试使用最新的 Pillow 而不是 PIL。

In [1]: import numpy as np
   ...: from PIL import Image
   ...: 

In [2]: img = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.uint8)

In [3]: img_nn_pil   = np.array(Image.fromarray(img).resize((9, 9), Image.NEAREST))

In [4]: print img_nn_pil
[[1 1 1 2 2 2 3 3 3]
 [1 1 1 2 2 2 3 3 3]
 [1 1 1 2 2 2 3 3 3]
 [4 4 4 5 5 5 6 6 6]
 [4 4 4 5 5 5 6 6 6]
 [4 4 4 5 5 5 6 6 6]
 [7 7 7 8 8 8 9 9 9]
 [7 7 7 8 8 8 9 9 9]
 [7 7 7 8 8 8 9 9 9]]

这只是 was fixed 的一个错误。