使用str在python中设置模块的属性

时间:2012-11-28 13:43:09

标签: string image-processing attributes python-3.x python-imaging-library

我正在尝试学习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'

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

1 个答案:

答案 0 :(得分: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)