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)
rectangle() Draws an rectangle. Parameters: xy – Four points to define the bounding box. Sequence of either [(x0, y0), (x1, y1)] or [x0, y0, x1, y1].
We can create a simple rectangle by defining a function that takes in two integers representing side length and side height. Then we can loop four times, using the forward() function to create a side representing either the length or height, then rotating the cursor 90 degrees with the right() function.
The 'ImageDraw' module provides simple 2D graphics support for Image Object. Generally, we use this module to create new images, annotate or retouch existing images and to generate graphics on the fly for web use. The graphics commands support the drawing of shapes and annotation of text.
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use. ImageDraw. Draw.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With