0

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

  • in Python you can't do something like `Image.i` if i is a string. But you can do `getattr(Image, i)` – Nik Sep 11 '22 at 07:04
  • In order to get help, you will need to provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – alec_djinn Sep 11 '22 at 07:06
  • Image doesn't have an attribute called `i`, the `i` in the loop is a string, it doesn't have anything to do with the Image objet, Python wont convert `Image.i` to `Image.FLIP_LEFT_RIGHT` if this is what you expect. – alec_djinn Sep 11 '22 at 07:49
  • @alec_djinn Hi thanks. That is exactly what I mean. So what do sudgest please. – Alain Michael Janith Schroter Sep 11 '22 at 08:12

1 Answers1

1

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))
alec_djinn
  • 10,104
  • 8
  • 46
  • 71
  • Hi, Thanks for the reply. I get a error saying : `ValueError: axes don't match array` Thanks & Best Regards – Alain Michael Janith Schroter Sep 11 '22 at 13:39
  • 1
    @SchroterMichael That is an error I can't check because I do not have the data (image) you are working with (you haven't provided a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example)). Also, it is a completely different error from the one you originally posted, so it should be a separate question. – alec_djinn Sep 11 '22 at 17:17