【问题标题】:Use str to set attribute for module in python在python中使用str设置模块的属性
【发布时间】:2012-11-16 09:17:05
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案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)
    

    【讨论】:

    • 当我尝试得到an error。我使用的是 Image.filter,因为它在我手动设置过滤器之前已经工作过(例如 Image.NEAREST、Image.ANTIALIAS 等);我是从here 那里得到的
    • Image.NEARESTImage.ANTIALIAS 是常量,可以直接引用。您可以将filter 设置为其中之一,然后将其传递给resize。但是Image.filter 不是Image 模块的定义属性。
    • 啊,是的,这行得通,我想我现在明白了。谢谢!编辑:由于某种原因,这也解决了我之前在缩小规模时遇到的问题。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 2021-11-24
    • 2015-01-30
    • 2021-11-30
    相关资源
    最近更新 更多