Use PIL function (transpose) in a for loop

Viewed 34

I am trying to use PIL's transform functions iteratively in a for loop. The code is as below please.

from PIL import Image
from skimage import data

flips = ['FLIP_LEFT_RIGHT','FLIP_TOP_BOTTOM']

coins = data.coins()

for i in flips:
    fliped = coins.transpose(Image.i) 
    display(fliped)

However, I get an output saying that Image has no attribute i

Output:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [22], in <cell line: 8>()
      6 coins = data.coins()
      8 for i in flips:
----> 9     fliped = coins.transpose(Image.i) 
     10     display(fliped)

File ~/newEnv/lib/python3.10/site-packages/PIL/Image.py:76, in __getattr__(name)
     74         deprecate(name, 10, f"{enum.__name__}.{name}")
     75         return enum[name]
---> 76 raise AttributeError(f"module '{__name__}' has no attribute '{name}'")

AttributeError: module 'PIL.Image' has no attribute 'i'

Would anyone be able to help me in this matter please.

Thanks & Best Regards Schroter Michael

1 Answers

I suggest you avoid the loop and call the methods explicitly.

You could use eval() and f-strings. But this is, in general, a bad idea and sign of poor code design.

for i in flips:
    flipped = eval(f'coins.transpose(Image.{i})') 
    display(flipped)

A safer way would be using getattr()

flipped = coins.transpose(getattr(Image.Transpose, i))
Related