简体   繁体   English

使用 PIL.resize 调整 JPG 大小会得到一个完全黑色的图像

[英]Resizing JPG using PIL.resize gives a completely black image

I'm using PIL to resize a JPG.我正在使用 PIL 来调整 JPG 的大小。 I'm expecting the same image, resized as output, but instead I get a correctly sized black box.我期待相同的图像,调整大小作为输出,但我得到了一个正确大小的黑框。 The new image file is completely devoid of any information, just an empty file.新的图像文件完全没有任何信息,只是一个空文件。 Here is an excerpt for my script:这是我的脚本的摘录:

basewidth = 300
img = Image.open(path_to_image)
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize))
img.save(dir + "/the_image.jpg")

I've tried resizing with Image.LANCZOS as the second argument, (defaults to Image.NEAREST with 1 argument), but it didn't make a difference.我尝试使用 Image.LANCZOS 作为第二个参数调整大小(默认为 Image.NEAREST 和 1 个参数),但没有任何区别。 I'm running Python3 on Ubunutu 16.04.我在 Ubunutu 16.04 上运行 Python3。 Any ideas on why the image file is empty?关于为什么图像文件为空的任何想法?

I also encountered the same issue when trying to resize an image with transparent background.在尝试调整具有透明背景的图像大小时,我也遇到了同样的问题。 The "resize" works after I add a white background to the image.在我为图像添加白色背景后,“调整大小”起作用。

Code to add a white background then resize the image:添加白色背景然后调整图像大小的代码:

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)

ref:参考:

  1. Other's code for making thumbnail 其他人制作缩略图的代码

  2. Python: Image resizing: keep proportion - add white background Python:图像大小调整:保持比例 - 添加白色背景

The simplest way to get to the bottom of this is to post your image!最简单的方法是发布您的图片! Failing that, we can check the various aspects of your image.否则,我们可以检查您图像的各个方面。

So, import Numpy and PIL, open your image and convert it to a Numpy ndarray , you can then inspect its characteristics:因此,导入 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) 

Now you can print and inspect the following things:现在您可以打印和检查以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM