【问题标题】:Why does PIL.resize() change colors?为什么 PIL.resize() 会改变颜色?
【发布时间】:2020-07-18 12:33:04
【问题描述】:

我正在尝试使用PIL 调整存储为 NumPy 数组的图像大小。但它似乎也可以跨通道标准化颜色,这是我不想要的。

如果我打印原始图像和更改图像的min()mean()max(),我得到以下信息:

0 139.3552607574856 255
0 92.91526075748563 235
0 62.96987110846718 207

0 116.63458655562165 255
0 162.5862423160817 255
0 189.97112433075552 255 

因此,生成的图像看起来像原来的蓝色油漆。

这是我用于调整大小的代码:

def resize(img, shape):
    pil_img = np2pil(img)
    pil_img = pil_img.resize((shape[1], shape[0]))
    np_img = pil2np(pil_img)
    return np_img


def np2pil(img):
    return Image.fromarray((img * 255).astype('uint8'))


def pil2np(img):
    np_img = np.asarray(img)

    if np_img.max() <= 1:
        return (np_img * 255).astype(int)
    else:
        return np_img

库版本:

numpy==1.19.0
Pillow==7.2.0

【问题讨论】:

  • 也尝试改变 resamplereducing_gap 参数,但它们在这里没有效果。

标签: python image numpy resize python-imaging-library


【解决方案1】:

根据您的输出,我假设原始输入图像的类型已经是np.uint8!?如果是这样,为什么要与255 相乘并在np2pil 中类型转换为np.uint8?您创建整数溢出集体(这解释了颜色的变化);实际调整大小与该问题无关!

如果我相应地更正np2pil

def np2pil(img):
    return Image.fromarray(img)

一切正常。对于某些图像,我得到以下“之前”和“之后”min()mean()max() 值:

0 103.00595625 255
0 91.01710625 255
0 85.2306375 255

1 103.01525 249
0 91.029375 255
0 85.249525 255

由于在调整大小过程中涉及插值,可能会出现细微差异。

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.5
NumPy:       1.19.4
Pillow:      8.1.0
----------------------------------------

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 2013-03-23
    • 1970-01-01
    相关资源
    最近更新 更多