Is there a way to specify the width of a rectangle in PIL?

waspinator picture waspinator · Dec 13, 2015 · Viewed 18.9k times · Source

I'm trying to draw thick rectangles onto an image using ImageDraw Module of PIL/pillow.

I tried using draw.rectangle([x1, y1, x2, y2], outline='yellow', width=3) but it doesn't seem to like the width parameter.

I can emulate what I want to do with a bunch of lines, but I was wondering if there is a proper way of doing it.

'''
coordinates = [(x1, y1), (x2, y2)]

    (x1, y1)
        *--------------
        |             |
        |             |
        |             |
        |             |
        |             |
        |             |
        --------------*
                      (x2, y2)

'''

def draw_rectangle(drawing, xy, outline='yellow', width=10):
    top_left = xy[0]
    bottom_right = xy[1]
    top_right = (xy[1][0], xy[0][1])
    bottom_left= (xy[0][0], xy[1][1])

    drawing.line([top_left, top_right], fill=outline, width=width)
    drawing.line([top_right, bottom_right], fill=outline, width=width)
    drawing.line([bottom_right, bottom_left], fill=outline, width=width)
    drawing.line([bottom_left, top_left], fill=outline, width=width)

Answer

Tim Krins picture Tim Krins · Feb 1, 2017

UPDATE - Pillow >= 5.3.0 rectangle now supports the width argument: PIL.ImageDraw.ImageDraw.rectangle(xy, fill=None, outline=None, width=0)

Previous answer:

Here is a method that draws a first initial rectangle, and then further rectangles going inwards - note, the line width is not centered along the border.

def draw_rectangle(draw, coordinates, color, width=1):
    for i in range(width):
        rect_start = (coordinates[0][0] - i, coordinates[0][1] - i)
        rect_end = (coordinates[1][0] + i, coordinates[1][1] + i)
        draw.rectangle((rect_start, rect_end), outline = color)

# example usage

im = Image.open(image_path)
drawing = ImageDraw.Draw(im)

top_left = (50, 50)
bottom_right = (100, 100)

outline_width = 10
outline_color = "black"

draw_rectangle(drawing, (top_left, bottom_right), color=outline_color, width=outline_width)