简体   繁体   中英

How to import two different things called the same from different modules?

I have two modules, first one is PIL, and the second one is wand, which I import from PIL and wand something called Image, and there is conflict, how do I overcome this problem?

from PIL import Image, ImageDraw

img = Image.new('RGB', (1600,1600), (0,0,0)) 
draw = ImageDraw.Draw(img)

red = (255,0,0)
for x in range(0, 1600, 200):
    for y in range(0, 1600, 200):
        draw.rectangle(((0+x,0+y),(99+x,99+y)), red)
for x in range(100, 1600, 200):
    for y in range(100, 1600, 200):
        draw.rectangle(((0+x,0+y),(99+x,99+y)), red)


from wand.image import Image
img.swirl(degree =-90)

img

I have this error...

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [9], in <cell line: 18>()
     14         draw.rectangle(((0+x,0+y),(99+x,99+y)), top)
     16 from wand.image import Image
---> 18 img.swirl(degree =-90)
     20 img

File /usr/lib/python3.10/site-packages/PIL/Image.py:548, in Image.__getattr__(self, name)
    541     warnings.warn(
    542         "Image categories are deprecated and will be removed in Pillow 10 "
    543         "(2023-07-01). Use is_animated instead.",
    544         DeprecationWarning,
    545         stacklevel=2,
    546     )
    547     return self._category
--> 548 raise AttributeError(name)

AttributeError: swirl

EDIT

from PIL import Image, ImageDraw

img = Image.new('RGB', (1600,1600), (0,0,0)) 
draw = ImageDraw.Draw(img)

top = (255,0,0)

for x in range(0, 1600, 200):
    for y in range(0, 1600, 200):
        draw.rectangle(((0+x,0+y),(99+x,99+y)), top)
        
for x in range(100, 1600, 200):
    for y in range(100, 1600, 200):
        draw.rectangle(((0+x,0+y),(99+x,99+y)), top)

from wand.image import Image as ooo
        
with ooo(img) as img:
    img.swirl(degree =-90)

img

I tried like this but got this error...

TypeError: image must be a wand.image.Image instance, not <PIL.Image.Image image mode=RGB size=1600x1600 at 0x7FE681031600>
from wand.image import Image as <an_alias>

You can either use an alias as mhmtsrmn described:

from wand.image import Image as <an_alias>

Or you can simply import modules and use full names:

import PIL
import wand.image

img = PIL.Image.new('RGB', (1600,1600), (0,0,0)) 
draw = PIL.ImageDraw.Draw(img)

with wand.image.Image(filename='file.png') as wand_img:
   ...

This might also help clear misunderstanding around your issue: .swirl() is a function on wand.image.Image , not on PIL.Image . Since these are two separate classes, you cannot simply call .swirl() on an instance of PIL.Image .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM