📜  Python PIL | ImageDraw.Draw.rectangle()(1)

📅  最后修改于: 2023-12-03 15:04:07.436000             🧑  作者: Mango

Python PIL | ImageDraw.Draw.rectangle()

PIL is the Python Imaging Library. It is a library that adds support for opening, manipulating, and saving many different image file formats. ImageDraw is a module that provides 2D graphics editing tools for image files.

In this article, we will focus on the 'Draw.rectangle()' function of the ImageDraw module. This function allows us to draw filled or unfilled rectangles on an image.

Syntax
ImageDraw.Draw.rectangle(xy, fill=None, outline=None, width=0)
Parameters
  • xy - The bounding box of the rectangle. It is a tuple of four integers (x0, y0, x1, y1), where (x0, y0) is the top left corner and (x1, y1) is the bottom right corner.
  • fill - The fill color of the rectangle. It can be a string, a tuple of RGB values, or None (transparent).
  • outline - The outline color of the rectangle. It can be a string, a tuple of RGB values, or None (no outline).
  • width - The width of the outline. It is an integer value, and the default value is 0 (no outline).
Example Usage
from PIL import Image, ImageDraw

# Open an image file
image = Image.open('example.jpg')
 
# Create an ImageDraw object
draw = ImageDraw.Draw(image)
 
# Draw a filled rectangle
draw.rectangle(xy=(50, 50, 100, 100), fill=(255, 0, 0))
 
# Draw an unfilled rectangle with a red outline
draw.rectangle(xy=(150, 50, 200, 100), outline=(255, 0, 0))
 
# Save the modified image
image.save('output.jpg')
Output

The above code will create a new image 'output.jpg' with the rectangles drawn on it. The first rectangle will be filled with red color, while the second rectangle will have a red outline.

Output Image

Conclusion

The 'Draw.rectangle()' function of the ImageDraw module provides a simple and effective way to draw rectangles on an image with various options like fill color, outline color, and width. This function can be used to create basic geometric shapes, highlight specific regions in an image, or draw bounding boxes for object detection tasks.