1

我正在尝试学习python(使用python3.2),现在我正在创建一个旨在缩放图像的程序:

from PIL import Image

def newSizeChoice():
    scale = input('Please enter the scale to be applied to the image: x')
    while float(scale) <= 0:
        scale = input('Invalid: scale must be positive. Please enter a new scale: x')
    return float(scale)

def bestFilter(x):
    if x < 1:
        filter = 'ANTIALIAS'
    elif x == 2:
        filter = 'BILINEAR'
    elif x == 4:
        filter = 'BICUBIC'
    else:
        filter = 'NEAREST'
    return filter

def resize(img, width, height, scale, filter):
    width = width * scale
    height = height * scale
    newimg = img.resize((width, height), Image.filter)
    newimg.save('images\\LargeCy.png')
    newimg.show()

img = Image.open('images\\cy.png')
pix = img.load()
width, height = img.size

scale = float(newSizeChoice())
filter = bestFilter(scale)
resize(img, width, height, scale, filter)

现在有点乱,因为我还在努力,但我的问题是当我在函数'bestFilter'中设置过滤器时,我无法使用它在函数'中设置过滤器调整大小'。我不断收到的错误:

Traceback (most recent call last):
  File "C:\Users\14davidson_a\Desktop\Projects\Exercises\ImageScaling.py", line 33, in <module>
    resize(img, width, height, scale, filter)
  File "C:\Users\14davidson_a\Desktop\Projects\Exercises\ImageScaling.py", line 23, in resize
    newimg = img.resize((width, height), Image.filter)
AttributeError: 'module' object has no attribute 'filter'

问题:有没有办法可以使用字符串来设置模块的属性?

4

1 回答 1

1

您正在尝试使用Image.filter未在Image模块上定义的 。也许您打算改用该filter方法的参数?

def resize(img, width, height, scale, filter):
    width = width * scale
    height = height * scale
    newimg = img.resize((width, height), filter)
    newimg.save('images\\LargeCy.png')
    newimg.show()

您不会将该filter参数用于该方法中的任何其他内容。

您需要更新bestFilter()函数以返回有效Image过滤器:

def bestFilter(x):
    if x < 1:
        filter = Image.ANTIALIAS
    elif x == 2:
        filter = Image.BILINEAR
    elif x == 4:
        filter = Image.BICUBIC
    else:
        filter = Image.NEAREST
    return filter

您可以通过使用映射来简化该功能:

_scale_to_filter = {
    1: Image.ANTIALIAS,
    2: Image.BILINEAR,
    4: Image.BICUBIC,
}
def bestFilter(x):
    return _scale_to_filter.get(x, Image.NEAREST)
于 2012-11-28T13:46:25.720 回答