简体   繁体   中英

Pillow: strange behavior using Draw.rectangle

I am drawing rectangles in a for-loop using Pillow. This worked on my desktop computer, but throwing a strange exception on my laptop.

This is the code (shortened):

from PIL import Image, ImageDraw
(...)
img = Image.open(sys.argv[1])
rimg = img.copy()
rimg_draw = ImageDraw.Draw(rimg)
(...)
(for-loop)
    rimg_draw.rectangle((x1, y1, x2, y2), fill=None, outline=(255, 0, 0))

This throws the following exception:

rimg_draw.rectangle((x1, y1, x2, y2), fill=None, outline=(255, 0, 0))
  File "/home/daniel/tensorflow2.7/lib/python2.7/site-packages/PIL/ImageDraw.py", line 203, in rectangle
    ink, fill = self._getink(outline, fill)
  File "/home/daniel/tensorflow2.7/lib/python2.7/site-packages/PIL/ImageDraw.py", line 124, in _getink
    ink = self.draw.draw_ink(ink, self.mode)
TypeError: function takes exactly 1 argument (3 given)

I do not understand, why this code fails: at Pillow's very own documentation PIL.ImageDraw.Draw.rectangle is defined with these arguments: rectangle(xy, fill=None, outline=None) .

Since the documentation explicitly lists the optional parameters fill and outline , why is Pillow complaining that it only takes 1 argument?

pip freeze says Pillows version is 3.3.1 .

If you read a grayscale image and try to draw a color rectangle on it, you'll get the error message: TypeError: function takes exactly 1 argument (3 given)

You need to give a color like outline=(255) , not a RGB color like outline=(255, 0, 0) . Otherwise you get the error because you're giving 3 color arguments, not one. If you do want to draw color onto a grayscale image, you can convert the image to RGB first: img = img.convert('RGB')

Edit: since many other people hit this problem too, I filed a bug against Pillow and they promptly made a fix . So this question and answer will hopefully soon be obsolete.

After slight adjustments to your code to make it run, I was not able to reproduce the exception.

from PIL import Image, ImageDraw

img = Image.open('testfig.png')
rimg = img.copy()
rimg_draw = ImageDraw.Draw(rimg)
rimg_draw.rectangle((10, 10, 30, 30), fill=None, outline=(255, 0, 0))
rimg.show()

However, I'm running Python 3.4.4 and Pillow 3.2.0 on my system. Is there any obvious difference in versions on your laptop compared to your desktop?

Can you have a deeper look at your code lines 124 and 203, respectively, or provide us with a working code snippet that creates this exception for you?

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