Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 745
daniel451 Avatar asked Aug 22 '16 12:08

daniel451


Video Answer


1 Answers

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.

like image 156
Ken Shirriff Avatar answered Sep 21 '22 11:09

Ken Shirriff