# How to draw shapes on images with Python (PIL): The Ultimate Guide

Geometric shapes are a big part of our online and offline worlds and mastering certain skills with regards to geometric shapes can provide propitious circumstances in both short term and long term. If you think about it for a moment, you will realize how much space geometric shapes occupy in our daily lives.

## Introduction: Geometric Shapes in Daily Life

For instance, most mobile phones, desks, beds, screens, laptops, buttons, books and windows have rectangular shapes while pizza is almost always circular (except Sicilian pizza) and its slices resemble triangles. Signs and flags concerning nautical, aviation, road and rail transportation can have circular, hexagonal or octagonal as well as triangular shapes.

Particularly for niche sub-domains under engineering, online businesses, digital image manipulation, architecture and e-learning geometric shapes are irreplaceable.

Some example fields would be:

• online learning,
• architectural design,
• computational photography,
• computer vision – (AI),
• web development – (UI/UX),
• online marketing and
• game development,
• manufacturing,
• contemporary art, digital art & NFTs

Geometric shapes get plenty of utilization in both digital and physical applications and the list above is a tiny representation of where we might see utilization of geometric shapes.

In this tutorial, we will use Python to draw geometric shapes, combine geometric shapes with images and demonstrate several use cases of geometric shapes through Python examples.

## What is a geometric shape?

A geometric shape is a two-dimensional or three-dimensional enclosed figure that has specific properties such as length, width, and height. Geometric shapes are the basis for more complex figures and structures in geometry and are often used in everyday life to describe and analyze the world around us.

Examples of geometric shapes include Square, Triangle, Circles, Rectangles, Hexagons, Pentagons, Octagons, Decagons, Parallelogram, Ellipse, Oval, Rhombus, Trapezoid, Kite, Star, Cone, Cylinder, Sphere, Cube, Cuboid, Prism, Pyramid, Torus .

## What to do with geometric shapes on images?

Understanding the utilization of geometric shapes can be useful in a vast spectrum of tasks in many industries. Although this tutorial focuses on creating geometric shapes on images. it might be useful to understand the scope of operations that can be carried out using geometric shapes. Here are some more examples.

• To create indicators & mark objects, items, areas of images
• To create logos, signs, quotes, frames, branding
• To create text on images with aesthetic semi-transparent background layer for increased readability
• To crop images in geometric shapes (triangle, circle, square, rounded rectangle, ellipse, pentagon, hexagon etc.)
• To manufacture objects, items, gadgets, electronics, furniture etc.
• To calculate positions of celestial bodies in outer space
• To publish books, calendars, notebooks
• To create or supplement modern art pieces.

## How to draw geometric shapes on images with Python's PIL (pillow) image editing library?

Python’s image editing library PIL (pillow) makes it very convenient for drawing geometric shapes on images and it provides many options to fine tune these drawings and shapes.

To draw geometric shapes we will use `ImageDraw` module from the PIL library. It can be imported as in the Python code below:

``````from PIL import Image, ImageDraw
``````

We are also importing the `Image` module as it will be used for opening images or creating new images.

Once we’ve imported the modules we need from the PIL library, we can start using them to draw geometric shapes.

Below, you can see detailed tutorial sections explaining how to draw various geometric shapes on an image, starting with the square.

### How to draw a square?

Square is a geometric shape with 4 equal sides and 4 right angles (90 degrees) between them.

Using Python’s `ImageDraw` module we can draw square shapes on any image and any coordinate on that image. We can also specify a fill color or outline color and we can even adjust transparency of the square by using more advanced Python image editing techniques. We can use 2 methods from ImageDraw to achieve a square shape.

• `ImageDraw.rectangle()`
• `ImageDraw.regular_polygon()`

In the next section, you can see a rectangle example drawn using the rectangle method. If you make sure the first argument has equal x and y values you will end up with a square instead of a rectangle. The first attribute defines the coordinates of the square (or rectangle) as following.

• `(x0, y0, x1, y1)`

If you check out the example below you will see that both x1 – x0 and y1 – y0 are equal which results in a square drawing. By increasing x1 or y1 you could create a rectangle as well.

From example below

• `(100, 100, 300, 300)`
• 300 – 100 = 200 (horizontal sides)
• 300 – 100 = 200 (vertical sides)
``````from PIL import Image, ImageDraw

img = Image.new("RGBA", (500,500))
draw = ImageDraw.Draw(img)

draw.rectangle((100,100,300,300), outline='teal', fill='orange', width=25)``````
``img.show()``

We get a cool rectangle with orange fill and teal outline with 25 pixel thickness.

### How to draw a rectangle?

A rectangle is also a:

• right-angled parallellogram (all parallel sides with 4 right angles)
• 4-sided polygon

A square is a unilateral rectangle but not all rectangles are square as they might have different side sizes.

Rectangle is one of the most commonly utilized geometric shape in the industrial world and it can be convenient in designing real estate property, furniture, digital work, images, consumer products, books and countless others.

• `ImageDraw.rectangle()`
• `ImageDraw.polygon()`
• `ImageDraw.regular_polygon()`
``````from PIL import Image, ImageDraw

img = Image.new("RGBA", (500,500))
draw = ImageDraw.Draw(img)

draw.rectangle((100,100,500,300), outline='navy', fill='mediumspringgreen', width=25)
img.show()
``````

### How to draw a circle?

Square is a geometric shape with 4 equal sides and 4 right angles (90 degrees) between them.

Using Python’s `ImageDraw` module we can draw square shapes on any image and any coordinate on that image. We can also specify a fill color or outline color and we can even adjust transparency of the square by using more advanced Python image editing techniques. We can use 2 methods from ImageDraw to achieve a square shape.

• `ImageDraw.rectangle()`
• `ImageDraw.regular_polygon()`
Here are the results of both images upon using the `.show()` method after our Python codes.
``````from PIL import Image, ImageDraw

img = Image.new("RGBA", (1000,1000))
draw = ImageDraw.Draw(img)
draw.ellipse((100,100,600,600), fill=(100,100,255,255),
outline="yellow", width=25)

img.show()``````
This Python examples demonstrates a perfect circle drawing however, you could also draw an ellipse using the same draw.ellipse method.

## Creative use of circle drawing on images

Here is another example without the fill argument. Circles below are used to outline the faces of two humans with different colors using Python PIL. Such outlines are often used in autonomous driving, computer vision and machine learning applications such as pattern recognition or face detection.

Check out the code and the resulting image below.

``````from PIL import Image, ImageDraw

img = Image.open("/home/humans.jpg")
draw = ImageDraw.Draw(img)
draw.ellipse((100,100,600,600), fill=(100,100,255,255),
outline="yellow", width=25)

img.show()``````

Another Python drawing example for consulting or branding opportunities. This technique can also be used to stamp hundreds of images using Python loops with the branding-related drawing.

Here is the Python code that’s used to create the image with 3 circles above.

``````from PIL import Image, ImageDraw

img = Image.open('/home/consulting_branding.jpg')

draw = ImageDraw.Draw(img)
x,y = 1900, 1200
margin = 100
draw.ellipse((x, y, x+margin, y+margin), fill=(100,100,255,255))
draw.ellipse((x+150, y, x+150+margin, y+margin), fill=(100,255,100,255))
draw.ellipse((x+300, y, x+300+margin, y+margin), fill=(255,100,100,255))

img.show()``````

### How to draw a triangle?

Square is a geometric shape with 4 equal sides and 4 right angles (90 degrees) between them.

Using Python’s `ImageDraw` module we can draw square shapes on any image and any coordinate on that image. We can also specify a fill color or outline color and we can even adjust transparency of the square by using more advanced Python image editing techniques. We can use 2 methods from ImageDraw to achieve a square shape.

• `ImageDraw.rectangle()`
• `ImageDraw.regular_polygon()`
``````from PIL import Image, ImageDraw, ImageFilter

img = Image.open('/home/usa.jpg')

draw = ImageDraw.Draw(img)
draw.regular_polygon((1400,400,250), 3, fill=(100,100,255,255))
``````
``````img.show()
``````
Here are the results of both images upon using the `.show()` method after our Python codes.

### How to draw polygons like pentagon, hexagon, septagon or octagon?

A polygon is a 2D shape that has multiple straight sides which form a closed plane figure.

A regular polygon is a equiangular and equilateral shape polygon shape. This means all regular polygons must have equal angles and equal sides.

Technically, many geometric shapes qualify as polygons. Some categorization examples are as following.

Polygons:

• triangle (3-sided),
• rectangle (4-sided),
• trapezoid (4-sided),
• parallelogram (4-sided),
• rhombus (4-equal-sided),
• kite (4-sided),
Regular Polygons:
• equilateral triangle (3-sided),
• square (4-sided),
• pentagon (5-sided),
• hexagon (6-sided),
• septagon (7-sided),
• octagon (8-sided),
• nonagon (9-sided),
• decagon (10-sided)
All regular polygons are also simple polygons.

We can conveniently draw polygons such as pentagon, hexagon, septagon, octagon nanogon (enneagon) or decagon etc.. using Python and the PIL (pillow library).

Using Python’s `ImageDraw` module we can initiate the draw object’s handle on an existing or new image. Then we can use `ImageDraw.regular_polygon()` and define the bounding circle and number of sides as well as some other attributes such as fill color.

Let’s draw a pentagon using the ImageDraw module from Python’s Pillow library.

Firstly, we can import the libraries we need and create a new image in RGBA mode. Check out our tutorial regarding RGBA color modes but RGBA allows us to have transparency layer (alpha layer) in case transparency is needed. 500×500 pixels should be a fine image dimension for the sake of this demonstration.

``````from PIL import Image, ImageDraw
img = Image.new("RGBA", (500,500))
``````

Next, we will need a draw object which we can use as a drawing handle. Draw object can be created on the image we just created. Then we can draw a pentagon which is nothing but a polygon with 5 sides. As the filling color let’s use “lightslategray”.

``````draw = ImageDraw.Draw(img)
draw.regular_polygon((100,100,100), 5, fill='lightslategray')``````

That’s it. It’s that easy drawing a sophisticated geometric shape on an image with Python. We can now show the image and check out how it came out.

``````img.show()
``````

## Drawing geometric shapes with text using Python

Of course you can articulate your coding project and create very interesting, utilitarian and meaningful shapes, objects and material.

For demonstration purposes, check out the stop sign created with a very similar Python code. This image involves an 8 sided red polygon shape with STOP written on it and it resembles the traffic sign stop.

Here’s the code which is required to create an image like above.

``````from PIL import Image, ImageDraw, ImageFont

img = Image.new("RGBA", (500,500))

draw = ImageDraw.Draw(img)
font = ImageFont.truetype('Inconsolata-Bold.ttf', 70)

draw.regular_polygon((200,200,200), 6, fill='seagreen')
draw.text((30,65), "STOP", fill='white', font=font)

img.show()
``````

We have an extensive tutorial about writing text on images using Python with quite a few cool Python examples so feel free to check that out as well for more ideas and technical skills as well.

## Advanced combinations of geometric shapes and text

The example below makes use of multiple creative elements and harmonizes computer code with visual aesthetics and intellectual property such as:

Result is a gorgeous and inspiring visual created with a few lines of Python code.
Here is the full code used to create the visual above.
``````# Importing modules and opening an image
from PIL import Image, ImageDraw, ImageFilter, ImageFont
img = Image.open('/home/sky.jpg').convert("RGBA")
background = Image.new("RGBA", img.size, (0,0,0,0))

# Drawing rounded rectangle with transparency on transparency layer and combining it with the opened image.
draw = ImageDraw.Draw(background)
draw.rounded_rectangle((200,400,2200,1900), 360, fill=(210,220,280,70), outline=None)
new_img = Image.composite(background, img, background)

# Typing inspirational quote and author's name on the new image with rounded rectangle/
draw2 = ImageDraw.Draw(new_img)
font1 = ImageFont.truetype('Inconsolata-Regular.ttf', 180,)
font2 = ImageFont.truetype('Inconsolata-Light.ttf', 170)
draw2.text((300,500), """
Today is your
opportunity to
build the tomorrow
you want.""", font=font1, fill=(50,50,50))
draw2.text((1100,1600), "KEN POIROT", font=font2, fill='teal')

new_img.show()

img.show()
``````

## Legal Aspects of Geometric Shapes

If you are working with geometric shapes you might eventually encounter a situation where law is also part of the equation.

Established artists, developers and businesses usually aim to protect their brand and/or work by registering trademarks or copyrights of their intellectual properties (IPs).

While both trademark and copyright are intellectual properties, they are easily distinguishable due to a significant difference. Trademark can be applied to an item concerning the brand of a company or an individual such as logo, name, product name, coloring etc that represents the company while copyright is usually applied for the content of a specific work.

It can be said that trademark is registered concerning the source of the work (brand name, logo etc.) while copyright applies to the work (product, art, text, drawing, design etc.) itself.

For example, design of a logo representing can be registered as a trademark for a company (given that it satisfies all the necessary requirements), while design work created for a project might be registered for copyright to eliminate IP theft.

While both trademarks and copyrights protect intellectual property, they serve different purposes and have different legal requirements for protection. Trademarks are used to prevent consumer confusion and protect the reputation and goodwill of a company or brand, while copyrights are used to protect the creative expression of an individual or group.

Additionally, the duration of protection for trademarks and copyrights also differs. Trademarks can be renewed indefinitely as long as they are in use, while copyrights typically last for the life of the creator plus a certain number of years after their death.

## Can I copyright a geometric shape?

In most cases, it is not possible to copyright a geometric shape. Copyright law protects original works of authorship, such as literary, artistic, or musical works. A geometric shape, by itself, is not considered a work of authorship and is not eligible for copyright protection.

However, there are some exceptions to this general rule. If a geometric shape is used as part of a logo, for example, the logo as a whole may be eligible for copyright protection. In this case, the geometric shape would be protected as part of the overall design of the logo.

Additionally, if a geometric shape is used as part of a sculpture or other artistic work, the sculpture or artwork as a whole may be eligible for copyright protection. In this case, the geometric shape would be protected as part of the overall creative expression of the work.

In general, however, a geometric shape by itself is not eligible for copyright protection. If you have specific questions about copyright and geometric shapes, it is best to consult with an attorney who specializes in copyright law.

## Can I register a geometric shape as trademark?

Similar to the copyright of geometric shapes it’s quite difficult to register a geometric shape as a trademark.

A company named IGT tried to register geometric shapes used in their game machines and expectedly they were refused to do that. Later when they appealed a similar outcome occurred after the previous refusal decision was reconfirmed by Trademark Trial and Appeal Board (TTAB) of United States Patent and Trademark Office (USPTO).

Accross the pond UK Government also has a very clear and informative guideline regarding untrademarkable items where it is stated that:

Trade marks are acceptable if they are:

• distinctive for the goods and services you provide

In other words they can be recognised as signs that differentiates your goods or service as different from someone else’s.

Since geometric shapes are most likely not distinctive for a single company, it is usually quite difficult to trademark them. Having said that there might be cases where a brand reaches enough distinction to actually be able to register some form of a geometric shape as their trademark. Please discuss with your attorney for professional advise.

USA: United States Patent and Trademark Office – Search USA Trademark Database

UK: Intellectual Property Office – Search UK Trademark Database

## Cropping Images in Geometric Shapes with Python

We also have a Python image cropping tutorial in which you can find Python examples to crop images in pretty much any geometric shape.

Here are some examples from that tutorial.
##### Rounded Rectangle

You can also use this tutorial about automated face recognition with Python and merge it with Batch Cropping techniques explained in this tutorial to apply automated circular face cropping to thousands or even millions of images.

## Why is it Important to Understand Geometric Shapes?

Understanding geometric shapes is important for several reasons. Here are some examples of why it is good to understand geometric shapes:

• Geometric shapes are a fundamental building block of mathematics, and understanding them is essential for success in math and science.
• Geometric shapes are used to represent and model many real-world objects and phenomena, such as buildings, bridges, and natural disasters.
• Geometric shapes are used to communicate and visualize complex ideas and concepts, such as in maps, diagrams, and technical drawings.
• Geometric shapes are used in art and design, and understanding their properties and relationships can help to create aesthetically pleasing and meaningful compositions.
• Geometric shapes are used in many everyday applications, such as in navigation, construction, engineering, and gaming, and understanding them can help to make these tasks easier and more efficient.

In summary, understanding geometric shapes is important because it is a fundamental skill that can be applied in many different areas and contexts. It can help you to better understand and solve problems, communicate and visualize ideas, and appreciate beauty and symmetry in the world around you.

## Summary

In this Python Tutorial we extensively covered different techniques to crop images using Python and its image editing PIL (pillow) library.

We took advantage of different modules from PIL such as Image, ImageDraw and ImageFont and we used several methods applied on Python PIL image objects. These methods are:

• .composite,
• .crop
• .draw,
• .text,
• .polygon,
• .rounded_rectangle,
• .ellipse,
• .open
• .show

You can, of course, save these generated image objects with the .save method  instead of just showing them with the .show method. You can refer to this quick tutorial how to save Python images.

We hope this computational photography tutorial was useful for our audience. Computational photography and digital image editing can be incredibly beneficial for organizations of all sizes and startups and they open many doors to impressive creativity.