使用PIL.resize调整JPG大小会产生全黑图像

时间:2019-07-16 07:39:36

标签: python python-3.x ubuntu python-imaging-library

我正在使用PIL调整JPG的大小。我期望使用与输出相同大小的图像,但是我得到的是正确尺寸的黑匣子。新图像文件完全没有任何信息,只是一个空文件。这是我的脚本的摘录:

alingItems

我尝试使用Image.LANCZOS作为第二个参数来调整大小(默认为Image.NEAREST,带有1个参数),但是没有任何区别。我在Ubunutu 16.04上运行Python3。为什么图像文件为空有任何想法?

2 个答案:

答案 0 :(得分:2)

在尝试调整具有透明背景的图像时,我也遇到了相同的问题。在将白色背景添加到图像后,“调整大小”有效。

添加白色背景然后调整图像大小的代码:

from PIL import Image

im = Image.open("path/to/img")

if im.mode == 'RGBA':
    alpha = im.split()[3]
    bgmask = alpha.point(lambda x: 255-x)
    im = im.convert('RGB')
    im.paste((255,255,255), None, bgmask)

im = im.resize((new_width, new_height), Image.ANTIALIAS)

参考:

  1. Other's code for making thumbnail

  2. Python: Image resizing: keep proportion - add white background

答案 1 :(得分:0)

最简单的方法就是发布图片!如果失败,我们可以检查图像的各个方面。

因此,导入Numpy和PIL,打开图像并将其转换为Numpy ndarray,然后可以检查其特征:

import numpy as np
from PIL import Image

# Open image
img = Image.open('unhappy.jpg')

# Convert to Numpy Array
n = np.array(img) 

现在您可以打印并检查以下内容:

n.shape       # we are expecting something like (1580, 1725, 3)

n.dtype       # we expect dtype('uint8')

n.max()       # if there's white in the image, we expect 255

n.min()       # if there's black in the image, we expect 0

n.mean()      # we expect some value between 50-200 for most images