Draw a Rectangle on an Image in Python
Hello Reader, after reading this article you will be able to draw a rectangle on an image in Python. For this task, we need the Python Imaging Library(PIL). PIL consists of various classes but, we need ImageDraw and Image Classes. Hence, the very first line of the script will be as follows
from PIL import Image, ImageDraw as D
Here, we have imported ImageDraw as D and Image Classes from PIL. In order to draw a rectangle on an Image, first, we have to open an Image. Hence let’s have a look at opening an Image using Image Class.
Here, i is the Image Object for the specified Image which is located at “Path_to_your_Image” in your Computer. The open Method returns an Image Object for the given Image. An Image Object is responsible for some basic Operations on Image like Opening, Closing, Cropping etc.
So, now let’s have a look at drawing a rectangle on given Image below
Here, we have created an Object (i.e. draw) for ImageDraw Class. It draws on any given Image (i.e. in our case i ). We’ve used the rectangle method to draw a Rectangle on a given Image. [(100,100),(250,250)] is the dimensions of the rectangle. The parameter outline determines the color of the Outline of the rectangle which is going to draw on the Image. You can either view or save the image with a rectangle by using show() and save() Methods.
Now, let’s dig into the example code to draw a rectangle on an Image in Python.
from PIL import Image, ImageDraw as D i=Image.open("Path_to_your_Image") draw=D.Draw(i) draw.rectangle([(100,100),(250,250)],outline="white") i.show()
The input for the above the code will be as follows
The output for the above code will be as follows