使用 PIL 调整大小以正确的方式替换 scipy.misc.imresize

Using PIL resize the right way to replace scipy.misc.imresize

我继承了遗留代码,由于 scipy 中的更新,我现在必须将 scipy.misc.imresize 替换为 PIL.Image.resize

这是原代码

# xn.shape = (519, 20)
xnr = scipy.misc.imresize(xn, (200, xn.shape[1]))
# xnr.shape = (200, 20) i think ?
SomeOtherArray[i, :] = xnr.flatten()

按照建议 here,我应该打电话给 np.array(Image.fromarray(arr).resize())

# xn.shape = (519, 20)
xnr = np.array(Image.fromarray(xn).resize((200, xn.shape[1])))
# xnr.shape = (20, 200) !!! Not (200, 20)
SomeOtherArray[i, :] = xnr.flatten()

问题 1:xnr = scipy.misc.imresize(xn, (200, xn.shape[1])) 给出 (200, 20)

的形状是否正确

问题 2:如何使在使用 PIL 后,xnr 是正确的,如先前在原始代码中预期的那样?

由于 Numpy 和 PIL 之间的维度顺序不同,这有点令人困惑。

PIL 中的图像大小为 (width, height)

但是,表示图像的 Numpy 数组的形状为 (height, width)

以下代码段说明了这一点:

import numpy as np
from numpy import random
from PIL import Image
import matplotlib.pyplot as plt

random.seed()
xn = random.randint(0, 255, (539,20), dtype=np.uint8)

im = Image.fromarray(xn)

print(im.size)

plt.imshow(im, cmap='gray', vmin=0, vmax=255)
plt.show()

所以当调用 Image.fromarray(xn) 时,你得到一张 20 宽 x 539 高的图片。

现在Image.fromarray(xn).resize((200, xn.shape[1]))是一张200宽×20高的图片,将原来的539高缩小为20,将原来的20宽拉伸为200得到。

如果你想保持原来的20宽,把539的高缩小到200,你应该这样做:

Image.fromarray(xn).resize((xn.shape[1], 200))

相比之下 scipy.misc.imresize(xn, (200, 20)) returns 具有形状 (200, 20) 的数组,如文档中所述:

size : int, float or tuple

  • int - Percentage of current size.

  • float - Fraction of current size.

  • tuple - Size of the output image (height, width).