使用PIL resize替换scipy.misc.imresize的正确方法

2024-03-28 17:44:24 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这是原始代码

# 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是正确的,正如先前在原始代码中预期的那样


Tags: 代码imagepilnpscipyarraymiscshape
1条回答
网友
1楼 · 发布于 2024-03-28 17:44:24

由于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宽x20高的图片,通过将原始539高度缩小到20,并将原始20宽度拉伸到200来获得

如果要保持原来的20宽度,并将539高度缩小到200,应执行以下操作:

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

相反scipy.misc.imresize(xn, (200, 20))返回一个具有(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).

相关问题 更多 >