ananaso
ananaso

Reputation: 167

Use str to set attribute for module in python

I'm trying to learn python (using python3.2), and right now I'm creating a program designed to scale images:

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)

It's a little bit of a mess right now, because I'm still working on it, but my problem is that when I set the filter in function 'bestFilter', I'm not able to use it to set the filter in function 'resize'. The error I keep getting:

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'

Question: Is there a way I can use a string to set the attribute for a module?

Upvotes: 1

Views: 413

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123072

You are trying to use Image.filter, which is not defined on the Image module. Perhaps you meant to use the filter argument of the method instead?

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()

You don't use the filter argument for anything else in that method.

You'll need to update your bestFilter() function to return a valid Image filter:

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

You could simplify that function by using a mapping:

_scale_to_filter = {
    1: Image.ANTIALIAS,
    2: Image.BILINEAR,
    4: Image.BICUBIC,
}
def bestFilter(x):
    return _scale_to_filter.get(x, Image.NEAREST)

Upvotes: 1

Related Questions