【问题标题】:Using PIL resize the right way to replace scipy.misc.imresize使用 PIL 调整大小的正确方法来替换 scipy.misc.imresize
【发布时间】:2020-04-07 09:46:27
【问题描述】:

我继承了旧代码,由于 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 是正确的,正如原始代码中先前所预期的那样?

【问题讨论】:

    标签: python scipy python-imaging-library image-resizing resize-image


    【解决方案1】:

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

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

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

    下面的 sn-p 说明了这一点:

    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)) 返回一个形状为 (200, 20) 的数组,如文档中所述:

    大小:整数、浮点数或元组

    • int - 当前大小的百分比。

    • float - 当前大小的分数。

    • tuple - 输出图像的大小(高度,宽度)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-01
      • 2016-10-21
      • 1970-01-01
      • 2011-11-11
      • 2012-06-03
      • 2016-11-19
      • 2012-12-01
      相关资源
      最近更新 更多